Wednesday, August 31, 2016

Redis command to get all available keys on Redis Cluster?

Leave a Comment

I am using this

redisManager.redisClient.keys('*example*', function (err, keys) { }) 

But it only gives keys from only one of the redis cluster. How can I get keys from all cluster?

1 Answers

Answers 1

You can't get keys for all nodes using a single command. You have to get keys for all nodes and merge them. Reference - https://github.com/antirez/redis/issues/1962

You can do something like.

var redis = require('redis');  redisConfig = new Array(     {"port": 1234, "host": "192.168.1.2"},     {"port": 5678, "host": "192.168.1.3"} );  keys    = new Array(); allKeys = new Array();  for(i = 0; i < redisConfig.length; i++){     redisClient = redis.createClient(redisConfig[i].port, redisConfig[i].host);           keys[i] = redisClient.keys('*example*', function (err, keys) {       allkeys = [...new Set([...allKeys ,...keys[i]])];     }) } 
Read More

What's the best practice to ensure atomic read of a database table using JDBC?

Leave a Comment

I have an java application reading from a database table for jobs to process, and I may have multiple instances of this application running on different servers as each job is independent. Once a job is picked up for processing, its status will be update to "running". What I want to make sure is the retrieval of to be processed jobs from each instance to be atomic, how can I achieve this using JDBC?

6 Answers

Answers 1

One approach that would be completely generic*, though perhaps slightly inefficient, would be to use a server-specific identifier to "claim" a job by first updating its status to that identifier, then retrieve the job based on that value. For example, if you were working with Windows servers on the same network then their server name would uniquely identify them. If your table looked like

JobID  JobName  Status -----  -------  ---------     1  Job_A    Completed     2  Job_B     3  Job_C 

where unclaimed jobs have a Status of NULL then your application running on SERVER1 could claim a job by doing setAutoCommit(true) followed by

UPDATE Jobs SET Status='SERVER1' WHERE JobID IN (     SELECT TOP 1 JobID FROM Jobs      WHERE Status IS NULL     ORDER BY JobID) 

If ExecuteUpdate returns 0 then there are no jobs pending. If it returns 1 then you can get the row with

SELECT JobID, ... FROM Jobs WHERE Status='SERVER1' 

and then update its Status to 'Running' with a parameterized query like

UPDATE Jobs SET Status='Running' WHERE JobID=? 

where you supply the JobID you retrieved from the previous SELECT.

*(i.e., not relying on any specific SQL extensions, explicit locking, or transaction handling)

Answers 2

Lock the table using whatever mechanism is supported by your database server.

For example, in Postgres it would be:

LOCK yourtable; 

And it's your table for the duration of the transaction.

Other databases will have something similar.

Answers 3

Use ResultSet that has CONCUR_READ_ONLY and TYPE_FORWARD_ONLY. If your database jdbc driver supports it, it will only return atomic read of your select time.

According to this documentation, (Table Summary of Visibility of Internal and External Changes)

forward-only cursor will only show your read time results. CONCUR_READ_ONLY will prevent your internal updates.

Answers 4

Problem

Take jobs ready to process and make their status running atomically.

Solution

No need for additional locks. Since an update operation is already atomic by itself in terms of the same query (see the excerpt from the docs below), update the jobs table, setting the status running to those that are ready to be processed and get the result of this update - it will be the jobs you took for processing.

Examples:

Postgres

UPDATE jobs SET status = 'running'   WHERE status is NULL RETURNING id; 

In terms of JDBC you can go similar to this:

String sql = "update ... returning ..."; boolean hasResult = statement.execute(sql); if (hasResult) {     ResultSet rs = statement.getResult(); } 

SQL Server

UPDATE jobs SET status = 'running'   WHERE status is NULL OUTPUT UPDATED.id; 

Excerpt from the Postgres documentation that shows how 2 transactions behave when doing UPDATE on the same table with the same query:

UPDATE will only find target rows that were committed as of the command start time. However, such a target row might have already been updated (or deleted or locked) by another concurrent transaction by the time it is found. In this case, the would-be updater will wait for the first updating transaction to commit or roll back (if it is still in progress).

Answers 5

When using databases of a transactional nature, one popular practice is to perform ROW-LEVEL LOCKING. Row-level locks prevent multiple transactions from modifying the same row. SELECT for UPDATE is an easy way to achieve this effect. Assuming you have a processes table:

SELECT process_id, status  from processes for UPDATE of status SKIP LOCKED; 

When done processing, issue

update processes set status = 'updated' where process_id = :process_id;             --from before 

Issue

commit; 

to release the lock.

Here's an actual example

Disclaimer: SELECT FOR UPDATE is a form of pessimistic locking and has its caveats as explained by Burleson. However, it might be a viable solution if the client is not web-based and extremely concurrent.

Answers 6

if you want to ensure proper work in concurrent environment in your specific example you can use the server name.

The table will look like:

JobID  JobName  Server  Status -----  -------  ------- ---------     1  Job_A    host-1  Completed     2  Job_A    host-2  Working     3  Job_B    host-3  Working 

if you have multiple instances on the same host add the process id too:

JobID  JobName  Server  ProcessID  Status -----  -------  ------- ---------- ---------     1  Job_A    host-1  1000       Completed     2  Job_A    host-2  1000       Working     3  Job_A    host-2  1001       Working     5  Job_B    host-3  1000       Working 
Read More

PHP / Mongo geoJSON Loop is not valid

Leave a Comment

I'm passing in some coordinates to mongo to do a geo search. It works fine if the coordinates don't intersect (for instance a figure eight). But when two lines intersect it gives the loop is not valid. Is there any way to find the intersection and split all these loops up?

Note there could be many.

EDIT: I added the sample query and error. Note that I understand why it's happening, I'm just wondering if there is some known way to split those loops up into separate polygon's (some algorithm or within Mongo).

Query:

db.items.find({     "address.location": {         "$geoWithin": {             "$geometry": {                 "type": "Polygon",                 "coordinates": [[                     [-97.209091, 49.905691],                     [-97.206345, 49.918072],                     [-97.178879, 49.919399],                     [-97.165146, 49.907903],                     [-97.164459, 49.892865],                     [-97.180939, 49.889326],                     [-97.197418, 49.895077],                     [-97.200165, 49.902596],                     [-97.203598, 49.919399],                     [-97.216644, 49.928682],                     [-97.244797, 49.927356],                     [-97.255096, 49.913209],                     [-97.209091, 49.905691]                 ]]             }         }     } }); 

Error:

Error: error: {     "waitedMS" : NumberLong(0),     "ok" : 0,     "errmsg" : "Loop is not valid: [             [ -97.209091, 49.905691 ]             [ -97.206345, 49.918072 ],             [ -97.17887899999999, 49.919399 ],             [ -97.16514599999999, 49.907903 ],             [ -97.16445899999999, 49.892865 ],             [ -97.180939, 49.889326 ],             [ -97.197418, 49.895077 ],             [ -97.200165, 49.902596 ],             [ -97.203598, 49.919399 ],             [ -97.216644, 49.928682 ],             [ -97.24479700000001, 49.927356 ],             [ -97.25509599999999, 49.913209 ],             [ -97.209091, 49.905691 ]         ]         Edges 1 and 7 cross.         Edge locations in degrees: [-97.2063450, 49.9180720]-[-97.1788790, 49.9193990]         and [-97.2001650, 49.9025960]-[-97.2035980, 49.9193990]     ",     "code" : 2 } 

2 Answers

Answers 1

It is because your coordinates are identical that creates an anomaly in the polygon shape: [-97.1788790, 49.9193990] and [-97.2035980, 49.9193990]. In your code remove or change any of the duplicate coordinate,

"coordinates": [[     [-97.209091, 49.905691],     [-97.206345, 49.918072],     [-97.178879, 49.919399], // this line     [-97.165146, 49.907903],     [-97.164459, 49.892865],     [-97.180939, 49.889326],     [-97.197418, 49.895077],     [-97.200165, 49.902596],     [-97.203598, 49.919399], // and this one     [-97.216644, 49.928682],     [-97.244797, 49.927356],     [-97.255096, 49.913209],     [-97.209091, 49.905691] ]] 

Answers 2

As I mentioned in comments the better tool to query spatial data would be to use PostGIS.

For example PostGIS have the ST_validReason() to find the problem with polygon and a st_makevalid to fix but if this is not an option then I would create a service available to your PHP script with shapely python library https://github.com/Toblerity/Shapely

http://toblerity.org/shapely/manual.html

The first premise of Shapely is that Python programmers should be able to perform PostGIS type geometry operations outside of an RDBMS

Certainly shapely is a popular tool, and you should get future help with in on StackOverflow or gis.stackexchange.com from more experienced users

I think the problem you are trying to solve is not as trivial as it sounds.

So I would perform following steps:

1 Find how to do it with shapely

similar questions: Splitting self-intersecting polygon only returned one polygon in shapely in Python

2 create a simple php service which will pass query details to python script

3 Shapely will not prevent the creation of invalid polygon, but exceptions will be raised when they are operated on. So basically on such exception, I would call the script from step 1.

If this is just for one of query, I would just use QGIS software ( import points as CSV, create a new shapefile layer ( of type polygon ), and use Numerical vertex edit plugin )

Read More

Tuesday, August 30, 2016

Nokogiri XSLT transform using multiple source XML files

Leave a Comment

I want to translate XML using Nokogiri. I built an XSL and it all works fine. I ALSO tested it in Intellij. My data comes from two XML files.

My problem occurs when I try to get Nokogiri to do the transform. I can't seem to find a way to get it to parse multiple source files.

This is the code I am using from the documentation:

require 'Nokogiri'  doc1 = Nokogiri::XML(File.read('F:/transcoder/xslt_repo/core_xml.xml',)) xslt = Nokogiri::XSLT(File.read('F:/transcoder/xslt_repo/google.xsl'))  puts xslt.transform(doc1) 

I tried:

require 'Nokogiri'  doc1 = Nokogiri::XML(File.read('F:/transcoder/xslt_repo/core_xml.xml',)) doc2 = Nokogiri::XML(File.read('F:/transcoder/xslt_repo/file_data.xml',)) xslt = Nokogiri::XSLT(File.read('F:/transcoder/xslt_repo/test.xsl'))  puts xslt.transform(doc1,doc2) 

However it seems transform only takes one argument, so at the moment I am only able to parse half the data I need:

<?xml version="1.0"?> <package package_id="LB000001">   <asset_metadata>     <series_title>test asset 1</series_title>     <season_title>Number 1</season_title>     <episode_title>ET 1</episode_title>     <episode_number>1</episode_number>     <license_start_date>21-07-2016</license_start_date>     <license_end_date>31-07-2016</license_end_date>     <rating>15</rating>     <synopsis>This is a test asset</synopsis>   </asset_metadata>   <video_file>     <file_name/>     <file_size/>     <check_sum/>   </video_file>   <image_1>     <file_name/>     <file_size/>     <check_sum/>   </image_1> </package> 

How can I get this to work?

Edit:

This is the core_metadata.xml which is created via a PHP code block and the data comes from a database.

<?xml version="1.0" encoding="utf-8"?> <manifest task_id="00000000373">   <asset_metadata>     <material_id>LB111111</material_id>     <series_title>This is a test</series_title>     <season_title>This is a test</season_title>     <season_number>1</season_number>     <episode_title>that test</episode_title>     <episode_number>2</episode_number>     <start_date>23-08-2016</start_date>     <end_date>31-08-2016</end_date>     <ratings>15</ratings>     <synopsis>this is a test</synopsis>   </asset_metadata>   <file_info>     <source_filename>LB111111</source_filename>     <number_of_segments>2</number_of_segments>     <segment_1 seg_1_start="00:00:10.000" seg_1_dur="00:01:00.000"/>     <segment_2 seg_2_start="00:02:00.000" seg_2_dur="00:05:00.000"/> <conform_profile definition="hd" aspect_ratio="16f16">ffmpeg -i S_PATH/F_NAME.mp4 SEG_CONFORM 2&gt; F:/Transcoder/logs/transcode_logs/LOG_FILE.txt</conform_profile> <transcode_profile profile_name="xbox" package_type="tar">ffmpeg -f concat -i T_PATH/CONFORM_LIST TRC_PATH/F_NAME.mp4 2&gt; F:/Transcoder/logs/transcode_logs/LOG_FILE.txt</transcode_profile>     <target_path>F:/profiles/xbox</target_path>   </file_info> </manifest> 

The second XML (file_date.xml) is dynamically create during the trancode process by nokogiri:

<?xml version="1.0"?> <file_data>   <video_file>     <file_name>LB111111_xbox_230816114438.mp4</file_name>     <file_size>141959922</file_size>     <md5_checksum>bac7670e55c0694059d3742285079cbf</md5_checksum>   </video_file>   <image_1>     <file_name>test</file_name>     <file_size>test</file_size>     <md5_checksum>test</md5_checksum>   </image_1> </file_data> 

I managed to work around this issue by making a call to by hard coding the file_date.xml into the XSLT file:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/">     <package>         <xsl:attribute name="package_id">             <xsl:value-of select="manifest/asset_metadata/material_id"/>         </xsl:attribute>         <asset_metadata>             <series_title>                 <xsl:value-of select="manifest/asset_metadata/series_title"/>             </series_title>             <season_title>                 <xsl:value-of select="manifest/asset_metadata/season_title"/>             </season_title>             <episode_title>                 <xsl:value-of select="manifest/asset_metadata/episode_title"/>             </episode_title>             <episode_number>                 <xsl:value-of select="manifest/asset_metadata/episode_number"/>             </episode_number>             <license_start_date>                 <xsl:value-of select="manifest/asset_metadata/start_date"/>             </license_start_date>             <license_end_date>                 <xsl:value-of select="manifest/asset_metadata/end_date"/>             </license_end_date>             <rating>                 <xsl:value-of select="manifest/asset_metadata/ratings"/>             </rating>             <synopsis>                 <xsl:value-of select="manifest/asset_metadata/synopsis"/>             </synopsis>         </asset_metadata>         <video_file>             <file_name>                 <xsl:value-of select="document('file_data.xml')/file_data/video_file/file_name"/>             </file_name>             <file_size>                 <xsl:value-of select="document('file_data.xml')/file_data/video_file/file_size"/>             </file_size>             <check_sum>                 <xsl:value-of select="document('file_data.xml')/file_data/video_file/md5_checksum"/>             </check_sum>         </video_file>         <image_1>             <file_name>                 <xsl:value-of select="document('file_data.xml')/file_data/image_1/file_name"/>             </file_name>             <file_size>                 <xsl:value-of select="document('file_data.xml')/file_data/image_1/file_size"/>             </file_size>             <check_sum>                 <xsl:value-of select="document('file_data.xml')/file_data/image_1/md5_checksum"/>             </check_sum>         </image_1>     </package> </xsl:template> 

I then use Saxon to do the transform:

xslt = "java -jar C:/SaxonHE9-7-0-7J/saxon9he.jar #{temp}core_metadata.xml #{temp}#{profile}.xsl > #{temp}#{file_name}.xml"  system("#{xslt}") 

I would love to find a way to do this without having to hardcode the file_date.xml into the XSLT.

1 Answers

Answers 1

Merge XML Documents and Transform

You'll have to do a bit of work to combine the XML content prior to your XLS-Transformation. @the-Tin-Man has a nice answer to a similar question in the archives, which can be adapted for your use case.

Let's say we have the following sample content:

<!--a.xml--> <?xml version="1.0"?> <xml>   <packages>     <package>Data here for A</package>     <package>Another Package</package>     </packages> </xml> <!--a.xml-->  <!--b.xml--> <?xml version="1.0"?> <xml>   <packages>     <package>B something something</package>     </packages> </xml> <!--end b.xml--> 

And we want to apply the following XLST template:

<!--transform.xslt--> <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="//packages">   <html>   <body>     <h2>Packages</h2>     <ol>       <xsl:for-each select="./package">         <li><xsl:value-of select="text()"/></li>       </xsl:for-each>     </ol>   </body>   </html> </xsl:template> </xsl:stylesheet> <!--end transform.xslt--> 

If we have parallel document structure, as in this case, we can merge the two XML documents' content together and pass that along for transformation.

require 'Nokogiri'  doc1 = Nokogiri::XML(File.read('./a.xml')) doc2 = Nokogiri::XML(File.read('./b.xml'))  moved_packages = doc2.search('package') doc1.at('/descendant::packages[1]').add_child(moved_packages)  xslt = Nokogiri::XSLT(File.read('./transform.xslt'))  puts xslt.transform(doc1) 

This would generate the following output:

<html><body> <h2>Packages</h2> <ol> <li>Data here for A</li> <li>Another Package</li> <li>B something something</li> </ol> </body></html> 

If your XML documents have varying structure, you may benefit from an intermediary XML nodeset that you add your content to, rather than the shortcut of merging document 2 content into document 1.

Read More

How can I check transcluded form's validity in directive?

Leave a Comment

Rewriting this question for clarification

How can I check transcluded form's validity in directive ? I would like to check myForm.$valid in link function of directive. I will inject different sort of forms into my directive or use my directive in different forms you can say

Difficulty is that scope is isolated and non of following answer worked for me.

Please find complete code here,

https://plnkr.co/edit/K3IrE5KVehWXFM9JEMvE?p=preview

I want to disable "Save" button when form is not valid.

4 Answers

Answers 1

To answer your primary question, you can expose and bind the form like any other model value:

angular.module("main", [])  		.directive("formDirective", formDirective);    function formDirective() {    return {      restrict: "A",      scope: {        formModel: "=formModel"      },      link: function (scope, element, attrs) {        scope.$watch("formModel.$valid", function (newValue, oldValue) {         console.log(newValue, oldValue);        });      }    }  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>  <div ng-app="main">  	<div form-directive form-model="myForm">  	   <div>  	   <form name="myForm">  	      <div>  	      	<input type="text" ng-model="name" required="required">  	      </div>           Valid: {{myForm.$valid}}  	   </form>  	   <div>  	</div>  </div>

However, as became clear from our conversation on chat, your overall problem is more complicated.

I have added a working example here: https://plnkr.co/edit/lkfdmc0PLRadfYFVhFAm?p=preview

The key aspects to realize here are:

  • You're opening a modal dialog with $uibModal.open, which will instantiate the referenced controller editCtrl and load your template editCtrl.html.
  • The loading process includes that Angular is compiling the template. This template includes a directive at the root level, so that directive needs to be compiled as well.
  • That directive uses transclusion and loads the template dialog.html. It is important to note here, that the scope of your esDlg directive is now available in the template of dialog.html, so you can access all properties defined in the scope of the directive declaration.
    You've already been making use of this with the dialog title and text.
  • All we need to do is to bind the validity information here as well, so that we can use it in the dialog.

Answers 2

angular.module("main", [])  		.directive("formDirective", formDirective);    function formDirective() {    return {      restrict: "A",      scope: {        formModel: "=name"      },      link: function (scope, element, attrs) {        scope.$watch("formModel.$valid", function (newValue, oldValue) {         console.log(newValue, oldValue);        });      }    }  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>  <div ng-app="main">  	<div my-directive>  	   <div>  	   <form name="myForm" form-directive>  	      <div>  	      	<input type="text" ng-model="name" required="required">  	      </div>           Valid: {{myForm.$valid}}  	   </form>  	   <div>  	</div>  </div>

I advise you to use angular-auto-validate

Answers 3

Are you defining the directive properly? Check out this plunker where validity's logged as you would expect.

function MyDirective() {   return {     restrict: 'AE',     scope: true,     link: function (scope, element, attrs) {       scope.$watch('myForm.$valid', function (validity) {         console.log(validity);       });     }   } } 

Answers 4

I created a plunk from your code and it seems to be working fine. Just remember, it will generate a log only when validity state of your form changes from valid to invalid or vice versa.

https://plnkr.co/edit/lW3e4p

  <div ng-app="my-app">     <div ng-controller="testCtrl">       <div my-directive>          <form name="myForm">            <input type="number" step="0.01" ng-model="rate" required>          </form>       </div>     </div>   </div> 

Angular:

angular.module('my-app').directive('myDirective', function() {   return {     link: function(scope, element, attr, mCtrl) {       scope.$watch('myForm.$valid', function(validity) {         console.log(validity);       })     }   }; }); 
Read More

Monday, August 29, 2016

Ipython notebook link to external notebook

Leave a Comment

I do not really know why, but I cannot link to files which are in a parent folder of the current working directory. I do start the notebook in the folder 04_documentation and would like to refer to a notebook in 02_calculations

The folder structure is:

  • Experiment #12345
    • 01_data
    • 02_calculations
      • sma_fit.ipynb
    • 03_plots
    • 04_documentation
      • current working directory

The link looks like [Link to working example](../02_calculations/sma_fit.ipynb)

If the file is in the same folder or a subfolder, everything works fine. However, I cannot jump to a parent folder(404 error). Any ideas why that is the case ?

1 Answers

Answers 1

Ipython notebook (3 and 2.3.1) answer in github

Because of security reasons you are not allowed to do that.

You could start the notebook in / but have the default dashboard be something else. But by design navigating up --notebook-dir (default to .) and going into folders that start with . is not possible.

Hope this is what you were trying.

Read More

FPS drops in SpriteKit

Leave a Comment

I'm developing a simple game with Swift & SpriteKit, and I've noticed FPS drops from 60 to 58-59 (and back). There is a noticeable lag when the drop occurs — it looks like 1 or 2 frames are dropped.

CPU load is about 20-25% and does not change a lot, memory usage is permanently about 8 MB.

Screenshot: App Screenshot

There are 6 object on screen: label, red object (Sprite), 2x green objects (Sprite), one box (Sprite) and "ground" (Rect shape node).

All objects except label have physics body (displayed with white borders).

Green and white objects are dynamically created, move from right to left and destroyed when offscreen:

func scheduleAddingLiquid() { let wait = SKAction.waitForDuration(NSTimeInterval(getRandomNumber(1, end: 3)))         let block = SKAction.runBlock({             [unowned self] in              let liquidNode = LiquidNode(texture: self.liquidTexture, sceneFrame: self.frame)             self.addChild(liquidNode)             liquidNode.move()              self.scheduleAddingLiquid()         })          let sequence = SKAction.sequence([wait, block])         runAction(sequence) 

and:

func move() {         let moveAction = SKAction.moveToX(-frame.width, duration: NSTimeInterval(3))         let removeBlock = SKAction.runBlock({             [unowned self] in              self.removeFromParent()             })          runAction(SKAction.sequence([moveAction, removeBlock]))     } 

Red object "jumps" on screen touch:

if touches.count > 0 && isHeroOnGround && heroNode != nil {             isHeroOnGround = false             heroNode.physicsBody?.velocity = CGVector(dx: 0, dy: 0)             heroNode.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 400))         } 

The lag occurs within random time interval after "jumping" (from about 0.5 to 1.5 seconds after jump).

The lag occurs not when collision occurs, just when red object is "in the air". And it occurs not every jump. The CPU load does not grow when FPS drops.

Tested on iOS 9.3, iPad mini 2.

Upd 1. Tested on iOS 9.3 iPhone 6 — FPS is about 50-55 for first few seconds, then it's constantly 60, without lags. So, it lags on iPad mini 2 only (I have only these two devices, cannot test on other ones).

UPD 2. I've commented out all objects creation code, except red figure. It's still lagging when "jumping". So, now I'm sure that it's related to applyImpulse method.

UPD 3. That's really, REALLY strange: I've removed all code from touchesBegan method, and it still lags on touches! The method is completely empty. I don't know why, but FPS drops if I click several times...

How to debug this?

1 Answers

Answers 1

It only having issues on the mini makes me think there is something wrong with your mini (or that particular package on your mini). Try making a new project, copy the files over, then run it again. Also, you said 9.3, but there is 9.3.1, 9.3.2, etc. The two devices could have had different builds.

So, first, ensure your iphone and iPad are running the same version of iOS.. Maybe there was a bug, or maybe they patched a bug (thus causing one to work and not the other).

Also, try running it on the different emulators... if it runs flawlessly on the emulators, then I'm even more suspect of the mini (in it's current configuration).

This way, you can also see if (maybe) the problem has to do with the orientation (widescreen of iphone vs 4:3 or whatever of iPad).

Sometimes, I've had "very strange" things happen to my project files (even without plugins) and simply creating a new project, copying all the files over fixed it. If it's lagging when you click on an empty "touchesBegan" ... makes me think something buggy with Xcode / your mini is at hand--since it only happens on that one device (thus we know so far)...

Other things to consider,

  1. Which version of Xcode are you using? Try The latest beta / go back to 7.3. Any differences?

  2. Do you have another computer you could try building the project from?

  3. If swapping out the [unowned self] or leaving it in didn't fix anything, then my suggestion would be to load up your code with print statements and see what's going on.

  4. If you used the Scene Editor to make the sprite nodes, delete them all and remake them, or try making them programmatically. This has fixed random bugs in some of my projects (for seemingly no reason).

We need more code / info, but the above should hopefully fix your problem.

Read More

Sunday, August 28, 2016

store info and pull out in array

Leave a Comment

I have a database with a row 'genre' this contains all types of genres for the movie seperated by a space like an example of this would be

Animation Comedy Horror 

They are all different genres so they need to be pulled out of the database and put in an array based on their genres I originally began coding this:

<? sql = "SELECT moviename,genre FROM movieHosting"; $query = mysql_query($sql); $row = mysql_fetch_object($query); ?> 

But I soon realized shortly after that every genre is going to be needed to be put in the array seperate if I did

$genreArray = array($row->genre); 

But this wont work it would generate an array like

$genreArray = array("Animation Comedy Horror"); 

But it needs to generate

$genreArray = array("Animation","Comedy","Horror"); 

8 Answers

Answers 1

Have you tried using the explode function?

Something like:

$genreArray = explode(" ", $row->genre); 

Answers 2

Here is more close to your logic.

$string = 'Animation Comedy Horror';     $genra = explode(" ", $string);     print_r($genra); //Array ( [0] => Animation [1] => Comedy [2] => Horror )      echo $genra[0]; //Animation      echo '<hr>'; // OR      foreach($genra as $value){         echo $value . '<br>';     }  // Output Animation Comedy Horror 

Hope our answers brings more clarification to your problem.

Answers 3

   $result = preg_split("/[\s,]+/", "Animation Comedy Horror");     print_r($result );     print_r(implode(",",$result)); 

OUT PUT

 Array ( [0] => Animation [1] => Comedy [2] => Horror )    Animation,Comedy,Horror 

Answers 4

Understand these and use accordingly.

<?php     $str = "Animation Comedy Horror";     $str_arr = explode(' ', $str);     print_r($str_arr);     $str_arr = split(' +', $str);     print_r($str_arr);     $str_arr = preg_split('/ +/', $str);     print_r($str_arr); ?> 

Check This : https://eval.in/532527

Also Understand about,

explode : http://php.net/manual/en/function.explode.php

preg-split : http://php.net/manual/en/function.preg-split.php

split : http://php.net/manual/en/function.split.php

split is depricated now.

Answers 5

WARNING
Stop using mysql_* functions, for multiple reasons : completely removed, officially deprecated, ... and for exhaustive list you can read this thread Why shouldn't I use mysql_* functions in PHP?, instead you can use mysqli_* or PDO

I think that it is a very bad design to store genre like you do it
How you will update your data ?
How to retrieve movies by genre ?

Each simple SQL operation will be a nightmare, instead of this, spend your time to correct your desgin, for example you can simply create a dedicated table from genre

ID | type ------------ 1  | Comedy 2  | Horror 3  | Mangas 4  | ...  5  | Animation 

And create an Entity Table that will associate the movie with [1, N] genre

MovieId | GenreId ----------------- 2       | 1 2       | 2 2       | 5 

Answers 6

Try using PHP's explode() function. This function expects 2 parameters, a delimiter, and a string. The delimiter is should be what you want to look for in the string to separate items. In practice this would look like:

$genreArray = explode(' ', $row->genre); 

Now $genreArray will look something like this (output generated from var_dump($genreArray)):

array(3) { [0]=> string(9) "Animation" [1]=> string(6) "Comedy" [2]=> string(6) "Horror" } 

Answers 7

$genreArray = preg_split("/[\s,]+/", "Animation Comedy Horror"); print_r($genreArray ); 

The output:

Array (     [0] => Animation     [1] => Comedy     [2] => Horror ) 

Answers 8

Try this

  1. Through multiple arrays:

    <? $sql = "SELECT moviename,genre FROM movieHosting"; $query = mysql_query($sql); $row = mysql_fetch_array($query); /* fetched value */ $moviename = $row['moviename']; $genre= $row['genre']; ?> 
  2. Through single arrays to produce result like $genreArray = array("Animation","Comedy","Horror");

    <? $sql = "SELECT moviename,genre FROM movieHosting"; $query = mysql_query($sql); $row = mysql_fetch_array($query); /* fetched value */ $array =array(); foreach($row as $r){     $moviename = $r['moviename'];     $genre = $r['genre'];     $array_push = array_push($array,$moviename,$genre);     print_r($array_push); } ?> 
Read More

Why can't my Core 1 library be seen in my ASP.NET Core 1.0 (MVC6) project?

Leave a Comment

I have a little class library (Core 1), separate so that other apps may also use it, and all those reasons. It has only POCO model classes and a DbContext derivative. Its project file looks as follows:

{     "version": "1.0.0-*",     "dependencies": {         "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",         "NETStandard.Library": "1.5.0-rc2-24027",         "System.ComponentModel.Annotations": "4.1.0"     },     "frameworks": {         "netstandard1.5": {             "imports": "dnxcore50"         }     } } 

Then I have an ASP.NET Core Web Application (.NET Core) that I wish to use the class library in. Nearly everywhere I look, and I've looked, says to just add the library to the main project's dependencies section of its project file. There it is, right at the top:

"dependencies": {     "WideWorld.Filing": "1.0.0.0",     "Microsoft.NETCore.App": {         "version": "1.0.0-rc2-3002702",         "type": "platform"     },     "Microsoft.ApplicationInsights.AspNetCore": "1.0.0-rc2-final", 

I can't even see the library namespace WideWorld.Filing in the main project, where I can, obviously, see its namespace, WideWorld.Office. I am very, very new to Core 1, and have only build monolith web applications before, so please excuse my ignorance if I'm missing something obvious.

If I do a package restore on the main project, I get three warnings in the log (and other stuff that looks harmless):

warn : Detected package downgrade: Microsoft.EntityFrameworkCore.SqlServer from 1.0.0 to 1.0.0-rc2-final  warn :  WideWorld.Office (>= 1.0.0) -> WideWorld.Filing (>= 1.0.0) -> Microsoft.EntityFrameworkCore.SqlServer (>= 1.0.0)  warn :  WideWorld.Office (>= 1.0.0) -> Microsoft.EntityFrameworkCore.SqlServer (>= 1.0.0-rc2-final) 

1 Answers

Answers 1

The issue is that you're mixing packages versions. For example the RTM and RC2 packages are not compatible. You should either target everything as RC2 (which I'd advise against) or take the more preferred approach and upgrade all package references to RTM, targeting version 1.0.0.

More details here:

Note, I have omitted the "import": "dnxcore50"

{     "version": "1.0.0-*",     "dependencies": {         "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",         "NETStandard.Library": "1.6.0",         "System.ComponentModel.Annotations": "4.1.0"     },     "frameworks": {         "netstandard1.5": { }     } } 

Likewise, in the other project.json do this:

"dependencies": {     "WideWorld.Filing": "1.0.0.0",     "Microsoft.NETCore.App": {         "version": "1.0.0",         "type": "platform"     },     "Microsoft.ApplicationInsights.AspNetCore": "1.0.0" 

Additional details on packages.

Read More

checkbox get disabled in ng-repeat of accordions

Leave a Comment

I have build a list of accordions, each accordion represent a group of items. I have used ng-repeat to iterate through group names,each group has a checkbox which indicate if it is chosen or not.

The example works fine for single group of accordion, but the moment I am putting the accordion inside ng-repeat, the checkbox can't be selected at all.

Here is the code, the main checkbox of each group title doesn't work apparently, I am try to figure out the reason for this.

My main Question is:

1.How can I make the checkboxes of Group1 and Group2 and Group3 active,so I can select them properly, In current situation, I can't select the checkboxes at all(of Group1,Group2 and Group3).

var app = angular.module('app',[]);    app.controller('mainCTRL',function($scope){    $('.collapse').collapse();    $scope.title="Hello World";    $scope.items1 = ['Group1','Group2','Group3']  })
.ui-checkbox {    display: none;  }  .ui-checkbox + label {    position: relative;    padding-left: 25px;    display: inline-block;    font-size: 14px;  }  .ui-checkbox + label:before {    background-color: #fff;    /**#fff*/    border: 1px solid #1279C6;    padding: 9px;    border-radius: 3px;    display: block;    position: absolute;    top: 0;    left: 0;    content: "";  }  .ui-checkbox:checked + label:before {    border: 1px solid #1279C6;    color: #99a1a7;  }  .ui-checkbox:checked + label:after {    content: '\2714';    font-size: 14px;    position: absolute;    top: 1px;    left: 4px;    color: #1279C6;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">  </script>  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>    <div ng-app="app" ng-controller="mainCTRL">  <div ng-repeat="item in items1">      <div class="panel-group driving-license-settings" id="accordion-{{$index}}">          <div class="panel panel-default">              <div class="panel-heading">                  <h4 class="panel-title">                      <a data-toggle="collapse" data-parent="#accordion-{{$index}}"                         data-target="#collapseOne-{{$index}}">                          <input type="checkbox" class="ui-checkbox" id="chk1-{{$index}}" value="">                          <label for="chk1-{{$index}}">{{item}}</label>                      </a>                  </h4>              </div>              <div id="collapseOne-{{$index}}" class="panel-collapse collapse ">                  <div class="panel-body">                      <div class="driving-license-kind">                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-1" value="">                              <label for="chk2-cb-{{item}}-1">A</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-2" value="">                              <label for="chk2-cb-{{item}}-2">B</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-3" value="">                              <label for="chk2-cb-{{item}}-3">C</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-4" value="">                              <label for="chk2-cb-{{item}}-4">D</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-5" value="">                              <label for="chk2-cb-{{item}}-5">E</label>                          </div>                      </div>                  </div>              </div>          </div>      </div>  </div>  </div>

2 Answers

Answers 1

The problem is because your checkboxes are nested inside anchors. Simply change:

<a data-toggle="collapse" data-parent="#accordion-{{$index}}"                        data-target="#collapseOne-{{$index}}"> 

To:

<div data-toggle="collapse" data-parent="#accordion-{{$index}}"                        data-target="#collapseOne-{{$index}}"> 

See working example:

var app = angular.module('app',[]);    app.controller('mainCTRL',function($scope){    $('.collapse').collapse();    $scope.title="Hello World";    $scope.items1 = ['Group1','Group2','Group3']  })
.ui-checkbox {    display: none;  }  .ui-checkbox + label {    position: relative;    padding-left: 25px;    display: inline-block;    font-size: 14px;  }  .ui-checkbox + label:before {    background-color: #fff;    /**#fff*/    border: 1px solid #1279C6;    padding: 9px;    border-radius: 3px;    display: block;    position: absolute;    top: 0;    left: 0;    content: "";  }  .ui-checkbox:checked + label:before {    border: 1px solid #1279C6;    color: #99a1a7;  }  .ui-checkbox:checked + label:after {    content: '\2714';    font-size: 14px;    position: absolute;    top: 1px;    left: 4px;    color: #1279C6;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">  </script>  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>    <div ng-app="app" ng-controller="mainCTRL">  <div ng-repeat="item in items1">      <div class="panel-group driving-license-settings" id="accordion-{{$index}}">          <div class="panel panel-default">              <div class="panel-heading">                  <h4 class="panel-title">                      <div data-toggle="collapse" data-parent="#accordion-{{$index}}"                         data-target="#collapseOne-{{$index}}">                          <input type="checkbox" class="ui-checkbox" id="chk1-{{$index}}" value="">                          <label for="chk1-{{$index}}">{{item}}</label>                      </div>                  </h4>              </div>              <div id="collapseOne-{{$index}}" class="panel-collapse collapse ">                  <div class="panel-body">                      <div class="driving-license-kind">                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-1" value="">                              <label for="chk2-cb-{{item}}-1">A</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-2" value="">                              <label for="chk2-cb-{{item}}-2">B</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-3" value="">                              <label for="chk2-cb-{{item}}-3">C</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-4" value="">                              <label for="chk2-cb-{{item}}-4">D</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-5" value="">                              <label for="chk2-cb-{{item}}-5">E</label>                          </div>                      </div>                  </div>              </div>          </div>      </div>  </div>  </div>

Answers 2

The problem is the ids you assigned. Make the ids unique, and the checkbox starts working. Here is the fixed snippet

var app = angular.module('app',[]);    app.controller('mainCTRL',function($scope){    $('.collapse').collapse();    $scope.title="Hello World";    $scope.items1 = ['Group1','Group2','Group3']  })
.ui-checkbox {    display: none;  }  .ui-checkbox + label {    position: relative;    padding-left: 25px;    display: inline-block;    font-size: 14px;  }  .ui-checkbox + label:before {    background-color: #fff;    /**#fff*/    border: 1px solid #1279C6;    padding: 9px;    border-radius: 3px;    display: block;    position: absolute;    top: 0;    left: 0;    content: "";  }  .ui-checkbox:checked + label:before {    border: 1px solid #1279C6;    color: #99a1a7;  }  .ui-checkbox:checked + label:after {    content: '\2714';    font-size: 14px;    position: absolute;    top: 1px;    left: 4px;    color: #1279C6;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">  </script>  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>    <div ng-app="app" ng-controller="mainCTRL">  <div ng-repeat="item in items1">      <div class="panel-group driving-license-settings" id="accordion-{{$index}}">          <div class="panel panel-default">              <div class="panel-heading">                  <h4 class="panel-title">                      <a data-toggle="collapse" data-parent="#accordion-{{$index}}"                         data-target="#collapseOne-{{$index}}">                          <input type="checkbox" class="ui-checkbox" id="chk1-{{$index}}" value="">                          <label for="chk1-{{$index}}">{{item}}</label>                      </a>                  </h4>              </div>              <div id="collapseOne-{{$index}}" class="panel-collapse collapse ">                  <div class="panel-body">                      <div class="driving-license-kind">                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-1" value="">                              <label for="chk2-cb-{{item}}-1">A</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-2" value="">                              <label for="chk2-cb-{{item}}-2">B</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-3" value="">                              <label for="chk2-cb-{{item}}-3">C</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-4" value="">                              <label for="chk2-cb-{{item}}-4">D</label>                          </div>                          <div class="checkbox">                              <input type="checkbox" class="ui-checkbox" id="chk2-cb-{{item}}-5" value="">                              <label for="chk2-cb-{{item}}-5">E</label>                          </div>                      </div>                  </div>              </div>          </div>      </div>  </div>  </div>

Read More

Friday, August 26, 2016

Best practice for storing ASP.NET Core Authorization claims when authenticating users against Active Directory?

Leave a Comment

I am creating an enterprise intranet ASP.NET Core MVC application. I want my users to authenticate using Active Directory and I want user authorizations (claims) stored in ApplicationDbContext.

I assume that I need to use Microsoft.AspNetCore.Identity and Microsoft.AspNetCore.Identity.EntityFrameworkCore to accomplish my goals. What is the best practice for storing ASP.NET Core Authorization claims when authenticating against Active Directory?

The following code will give me access to the current windows user security context (current logged in user), from within the pipeline. Somehow I need to map the user with associated Microsoft.AspNetCore.Identity claims?

 app.Use(async (context, next) =>  {       var identity = (ClaimsIdentity) context.User.Identity;       await next.Invoke();  }); 

Thanks in advance for the help!

0 Answers

Read More

Thursday, August 25, 2016

Mongoose text index on nested schema field

Leave a Comment

I have the following schema:

const Schema = ({   metadata: {     title: String,     ...   },   ...  }); 

and I'm looking to create a a text index on metadata.title. I can create a text index successfully on any first level property, but I'm running into trouble with the nested title.

I've tried the following code, to no avail. Is my syntax wrong? I've had no luck with docs...

Schema.index({ 'metadata.title': 'text' }); 

Searching:

Schema   .find(     { $text : { $search : req.params.query } },     { score : { $meta: "textScore" } }) 

2 Answers

Answers 1

It turns out what I had originally was correct, as pointed out by @JohnnyHK. I must have had some other error that caused the index to not work...

Answers 2

const Schema = ({    metadata: {      title: {        type: String,        index: true        }      ...    },    ...    });

Read More

CSS3 Animation Trigger with JQuery Click to Other Element

Leave a Comment

I have a reddit-like upvote/downvote situation going on in my Rails app and I'm trying to make a CSS3 animation so that when the user clicks any of the downvote links it triggers the animation.

I'm using JQuery like this:

<div class="animations">   <%= image_tag "ballerino.png", class: "fixed no-display", id: "to-animate", style: "margin-top: 80px; width: 40%" %>    <script>     $("#downvote").on('click',function() {       $('#to-animate').removeClass('fixed');       $('#to-animate').removeClass('no-display');       $('#to-animate').addClass('animation-left-to-right');     });   </script>  </div> <!-- animations --> 

With this further on down the page as a rendered partial for each Joke object:

<div class="text-center col-xs-1">   <% if current_user %>     <div class="width: 100%"><%= link_to " ", joke_up_vote_path(joke), id: "upvote", class: 'glyphicon glyphicon-chevron-up', method: :post, style: "margin-right: 0; margin-left: 0" %></div>   <% else %>     <div class="width: 100%"><%= link_to " ", new_user_session_path, id: "upvote", class: 'glyphicon glyphicon-chevron-up', method: :post, style: "margin-right: 0; margin-left: 0" %></div>   <% end %>   <div class="width: 100%"><h3 style="margin-top: 0; margin-bottom: 0"><strong><%= joke.points %></strong></h3></div>   <% if current_user %>     <div class="width: 100%"><%= link_to " ", joke_down_vote_path(joke), id: "downvote", class: 'glyphicon glyphicon-chevron-down', method: :post, style: "margin-right: 0; margin-left: 0" %></div>   <% else %>     <div class="width: 100%"><%= link_to " ", new_user_session_path, id: "downvote", class: 'glyphicon glyphicon-chevron-down', method: :post, style: "margin-right: 0; margin-left: 0" %></div>   <% end %> </div> 

And finally, here's my CSS for my animations from my application.scss file:

/* ANIMATIONS */  .animation-left-to-right{   animation: l-r-ballerina linear 4s;   animation-iteration-count: 1;   transform-origin: 50% 50%;   animation-fill-mode:forwards; /*when the spec is finished*/   -webkit-animation: l-r-ballerina linear 4s;   -webkit-animation-iteration-count: 1;   -webkit-transform-origin: 50% 50%;   -webkit-animation-fill-mode:forwards; /*Chrome 16+, Safari 4+*/   -moz-animation: l-r-ballerina linear 4s;   -moz-animation-iteration-count: 1;   -moz-transform-origin: 50% 50%;   -moz-animation-fill-mode:forwards; /*FF 5+*/   -o-animation: l-r-ballerina linear 4s;   -o-animation-iteration-count: 1;   -o-transform-origin: 50% 50%;   -o-animation-fill-mode:forwards; /*Not implemented yet*/   -ms-animation: l-r-ballerina linear 4s;   -ms-animation-iteration-count: 1;   -ms-transform-origin: 50% 50%;   -ms-animation-fill-mode:forwards; /*IE 10+*/ }  @keyframes l-r-ballerina{   0% { transform:  translate(-400px,0px)  rotate(0deg) ; }   10% { transform:  translate(-200px,0px)  rotate(-10deg) ; }   20% { transform:  translate(-100px,0px)  rotate(10deg) ; }   30% { transform:  translate(0px,0px)  rotate(-10deg) ; }   40% { transform:  translate(100px,0px)  rotate(10deg) ; }   50% { transform:  translate(300px,0px)  rotate(-10deg) ; }   100% { transform:  translate(3000px,0px)  rotate(-10deg) ; } }  @-moz-keyframes l-r-ballerina{   0% { -moz-transform:  translate(-400px,0px)  rotate(0deg) ; }   10% { -moz-transform:  translate(-200px,0px)  rotate(-10deg) ; }   20% { -moz-transform:  translate(-100px,0px)  rotate(10deg) ;  }   30% { -moz-transform:  translate(0px,0px)  rotate(-10deg) ; }   40% { -moz-transform:  translate(100px,0px)  rotate(10deg) ; }   50% { -moz-transform:  translate(300px,0px)  rotate(-10deg) ; }   100% {-moz-transform:  translate(3000px,0px)  rotate(-10deg) ; } }  @-webkit-keyframes l-r-ballerina {   0% { -webkit-transform:  translate(-400px,0px)  rotate(0deg) ; }   10% { -webkit-transform:  translate(-200px,0px)  rotate(-10deg) ; }   20% { -webkit-transform:  translate(-100px,0px)  rotate(10deg) ; }   30% { -webkit-transform:  translate(0px,0px)  rotate(-10deg) ; }   40% { -webkit-transform:  translate(100px,0px)  rotate(10deg) ; }   50% { -webkit-transform:  translate(300px,0px)  rotate(-10deg) ; }   100% { -webkit-transform:  translate(3000px,0px)  rotate(-10deg) ; } }  @-o-keyframes l-r-ballerina {   0% { -o-transform:  translate(-400px,0px)  rotate(0deg) ; }   10% { -o-transform:  translate(-200px,0px)  rotate(-10deg) ; }   20% { -o-transform:  translate(-100px,0px)  rotate(10deg) ; }   30% { -o-transform:  translate(0px,0px)  rotate(-10deg) ; }   40% { -o-transform:  translate(100px,0px)  rotate(10deg) ; }   50% { -o-transform:  translate(300px,0px)  rotate(-10deg) ; }   100% { -o-transform:  translate(3000px,0px)  rotate(-10deg) ; } }  @-ms-keyframes l-r-ballerina {   0% { -ms-transform:  translate(-400px,0px)  rotate(0deg) ; }   10% { -ms-transform:  translate(-200px,0px)  rotate(-10deg) ; }   20% { -ms-transform:  translate(-100px,0px)  rotate(10deg) ; }   30% { -ms-transform:  translate(0px,0px)  rotate(-10deg) ; }   40% { -ms-transform:  translate(100px,0px)  rotate(10deg) ; }   50% { -ms-transform:  translate(300px,0px)  rotate(-10deg) ; }   100% { -ms-transform:  translate(3000px,0px)  rotate(-10deg) ; } }  .fixed {   position: fixed; }  .no-display {   display: none; } 

Can anyone help me troubleshoot this? I'm new to animations and to JQuery...a bad combination.

ADDED FIDDLE

$(".downvote").on('click', function() {    $('#to-animate').removeClass('fixed');    $('#to-animate').removeClass('no-display');    $('#to-animate').addClass('animation-left-to-right');  });
/* ANIMATIONS */    .animation-left-to-right {    animation: l-r-ballerina linear 4s;    animation-iteration-count: 1;    transform-origin: 50% 50%;    animation-fill-mode: forwards;    /*when the spec is finished*/    -webkit-animation: l-r-ballerina linear 4s;    -webkit-animation-iteration-count: 1;    -webkit-transform-origin: 50% 50%;    -webkit-animation-fill-mode: forwards;    /*Chrome 16+, Safari 4+*/    -moz-animation: l-r-ballerina linear 4s;    -moz-animation-iteration-count: 1;    -moz-transform-origin: 50% 50%;    -moz-animation-fill-mode: forwards;    /*FF 5+*/    -o-animation: l-r-ballerina linear 4s;    -o-animation-iteration-count: 1;    -o-transform-origin: 50% 50%;    -o-animation-fill-mode: forwards;    /*Not implemented yet*/    -ms-animation: l-r-ballerina linear 4s;    -ms-animation-iteration-count: 1;    -ms-transform-origin: 50% 50%;    -ms-animation-fill-mode: forwards;    /*IE 10+*/  }  @keyframes l-r-ballerina {    0% {      transform: translate(-400px, 0px) rotate(0deg);    }    10% {      transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      transform: translate(-100px, 0px) rotate(10deg);    }    30% {      transform: translate(0px, 0px) rotate(-10deg);    }    40% {      transform: translate(100px, 0px) rotate(10deg);    }    50% {      transform: translate(300px, 0px) rotate(-10deg);    }    100% {      transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-moz-keyframes l-r-ballerina {    0% {      -moz-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -moz-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -moz-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -moz-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -moz-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -moz-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -moz-transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-webkit-keyframes l-r-ballerina {    0% {      -webkit-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -webkit-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -webkit-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -webkit-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -webkit-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -webkit-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -webkit-transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-o-keyframes l-r-ballerina {    0% {      -o-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -o-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -o-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -o-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -o-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -o-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -o-transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-ms-keyframes l-r-ballerina {    0% {      -ms-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -ms-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -ms-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -ms-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -ms-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -ms-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -ms-transform: translate(3000px, 0px) rotate(-10deg);    }  }  .fixed {    position: fixed;  }  .no-display {    display: none;  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>    <div class="fixed no-display" id="to-animate" style="margin-top: 80px; width: 40%; background: blue; height: 20px;">    Box to Animate  </div>    <div class="text-center col-xs-1">        <div class="width: 100%">      <a class="upvote glyphicon glyphicon-chevron-up" style="margin-right: 0; margin-left: 0" rel="nofollow" data-method="post" href="#"></a>    </div>    <div class="width: 100%">      <h3 style="margin-top: 0; margin-bottom: 0"><strong>0</strong></h3>    </div>    <div class="width: 100%">      <a class="downvote glyphicon glyphicon-chevron-down" style="margin-right: 0; margin-left: 0" rel="nofollow" data-method="post" href="#"></a>    </div>  </div>

I think this simulates the problem. I added a div instead of an image, but with the same id so it's visible...

2 Answers

Answers 1

I am not really sure that I understood your problem, but are you expecting something like this ?

$(".downvote").on('click', function() {    //$('#to-animate').removeClass('fixed');    $('#to-animate').removeClass('no-display');    $('#to-animate').addClass('animation-left-to-right');  });
/* ANIMATIONS */    .animation-left-to-right {    animation: l-r-ballerina linear 4s;    animation-iteration-count: 1;    transform-origin: 50% 50%;    animation-fill-mode: forwards;    /*when the spec is finished*/    -webkit-animation: l-r-ballerina linear 4s;    -webkit-animation-iteration-count: 1;    -webkit-transform-origin: 50% 50%;    -webkit-animation-fill-mode: forwards;    /*Chrome 16+, Safari 4+*/    -moz-animation: l-r-ballerina linear 4s;    -moz-animation-iteration-count: 1;    -moz-transform-origin: 50% 50%;    -moz-animation-fill-mode: forwards;    /*FF 5+*/    -o-animation: l-r-ballerina linear 4s;    -o-animation-iteration-count: 1;    -o-transform-origin: 50% 50%;    -o-animation-fill-mode: forwards;    /*Not implemented yet*/    -ms-animation: l-r-ballerina linear 4s;    -ms-animation-iteration-count: 1;    -ms-transform-origin: 50% 50%;    -ms-animation-fill-mode: forwards;    /*IE 10+*/  }  @keyframes l-r-ballerina {    0% {      transform: translate(-400px, 0px) rotate(0deg);    }    10% {      transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      transform: translate(-100px, 0px) rotate(10deg);    }    30% {      transform: translate(0px, 0px) rotate(-10deg);    }    40% {      transform: translate(100px, 0px) rotate(10deg);    }    50% {      transform: translate(300px, 0px) rotate(-10deg);    }    100% {      transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-moz-keyframes l-r-ballerina {    0% {      -moz-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -moz-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -moz-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -moz-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -moz-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -moz-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -moz-transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-webkit-keyframes l-r-ballerina {    0% {      -webkit-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -webkit-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -webkit-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -webkit-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -webkit-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -webkit-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -webkit-transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-o-keyframes l-r-ballerina {    0% {      -o-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -o-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -o-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -o-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -o-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -o-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -o-transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-ms-keyframes l-r-ballerina {    0% {      -ms-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -ms-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -ms-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -ms-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -ms-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -ms-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -ms-transform: translate(3000px, 0px) rotate(-10deg);    }  }  .fixed {    position: fixed;  }  .no-display {    display: none;  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>        <div class="fixed no-display" id="to-animate" style="margin-top: 80px; width: 40%; background: blue; height: 20px;">    Box to Animate  </div>    <div class="text-center col-xs-1">        <div class="width: 100%">      <a class="upvote glyphicon glyphicon-chevron-up" style="margin-right: 0; margin-left: 0" rel="nofollow" data-method="post" href="#"></a>    </div>    <div class="width: 100%">      <h3 style="margin-top: 0; margin-bottom: 0"><strong>0</strong></h3>    </div>    <div class="width: 100%">      <a class="downvote glyphicon glyphicon-chevron-down" style="margin-right: 0; margin-left: 0" rel="nofollow" data-method="post" href="#"></a>    </div>  </div>

Answers 2

If you want your page to refresh after the animation end fires or the transition end event fires, you'll need to listen for one or the other. I've added a listener for both including browser prefixes. Your animation is long and continues off screen, so it looks pretty quirky, but you get the general idea.

$(".downvote").on('click', function() {    var href = "http://stackoverflow.com/questions/38934608/css3-animation-trigger-with-jquery-click-to-other-element";     $('#to-animate').one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend webkitAnimationEnd oanimationend oAnimationEnd msAnimationEnd animationend", function(e) {      //Stub handler      //Your logic goes here      if(confirm("Detected " + e.type + " event.  Redirect to " + href + "?")){        window.location.href = href;      }      })    $('#to-animate').removeClass('fixed');    $('#to-animate').removeClass('no-display');    $('#to-animate').addClass('animation-left-to-right');  });
/* ANIMATIONS */    .animation-left-to-right {    animation: l-r-ballerina linear 4s;    animation-iteration-count: 1;    transform-origin: 50% 50%;    animation-fill-mode: forwards;    /*when the spec is finished*/    -webkit-animation: l-r-ballerina linear 4s;    -webkit-animation-iteration-count: 1;    -webkit-transform-origin: 50% 50%;    -webkit-animation-fill-mode: forwards;    /*Chrome 16+, Safari 4+*/    -moz-animation: l-r-ballerina linear 4s;    -moz-animation-iteration-count: 1;    -moz-transform-origin: 50% 50%;    -moz-animation-fill-mode: forwards;    /*FF 5+*/    -o-animation: l-r-ballerina linear 4s;    -o-animation-iteration-count: 1;    -o-transform-origin: 50% 50%;    -o-animation-fill-mode: forwards;    /*Not implemented yet*/    -ms-animation: l-r-ballerina linear 4s;    -ms-animation-iteration-count: 1;    -ms-transform-origin: 50% 50%;    -ms-animation-fill-mode: forwards;    /*IE 10+*/  }  @keyframes l-r-ballerina {    0% {      transform: translate(-400px, 0px) rotate(0deg);    }    10% {      transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      transform: translate(-100px, 0px) rotate(10deg);    }    30% {      transform: translate(0px, 0px) rotate(-10deg);    }    40% {      transform: translate(100px, 0px) rotate(10deg);    }    50% {      transform: translate(300px, 0px) rotate(-10deg);    }    100% {      transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-moz-keyframes l-r-ballerina {    0% {      -moz-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -moz-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -moz-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -moz-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -moz-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -moz-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -moz-transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-webkit-keyframes l-r-ballerina {    0% {      -webkit-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -webkit-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -webkit-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -webkit-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -webkit-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -webkit-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -webkit-transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-o-keyframes l-r-ballerina {    0% {      -o-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -o-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -o-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -o-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -o-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -o-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -o-transform: translate(3000px, 0px) rotate(-10deg);    }  }  @-ms-keyframes l-r-ballerina {    0% {      -ms-transform: translate(-400px, 0px) rotate(0deg);    }    10% {      -ms-transform: translate(-200px, 0px) rotate(-10deg);    }    20% {      -ms-transform: translate(-100px, 0px) rotate(10deg);    }    30% {      -ms-transform: translate(0px, 0px) rotate(-10deg);    }    40% {      -ms-transform: translate(100px, 0px) rotate(10deg);    }    50% {      -ms-transform: translate(300px, 0px) rotate(-10deg);    }    100% {      -ms-transform: translate(3000px, 0px) rotate(-10deg);    }  }  .fixed {    position: fixed;  }  .no-display {    display: none;  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>    <div class="fixed no-display" id="to-animate" style="margin-top: 80px; width: 40%; background: blue; height: 20px;">    Box to Animate  </div>    <div class="text-center col-xs-1">        <div class="width: 100%">      <a class="upvote glyphicon glyphicon-chevron-up" style="margin-right: 0; margin-left: 0" rel="nofollow" data-method="post" href="#"></a>    </div>    <div class="width: 100%">      <h3 style="margin-top: 0; margin-bottom: 0"><strong>0</strong></h3>    </div>    <div class="width: 100%">      <a class="downvote glyphicon glyphicon-chevron-down" style="margin-right: 0; margin-left: 0" rel="nofollow" data-method="post" href="#"></a>    </div>  </div>

Read More

Wednesday, August 24, 2016

Unique popup window using window.open in an iframe

Leave a Comment

I have an iFrame with a window open(url,uniqueID,windowparams). The iFrame is located on a single page app and hosted in another server. Everytime I refresh or change the page then return to the IFrame page, then try to initiate the same window.open. Instead of refreshing the already opened window, it creates an instance of the same window. Upon checking the window.name of each popup, it returns the same uniqueID as its window name. If the url is set blank it behaves as expected. But when a url is set, it creates a new instance of the window.

  • Do iFrame window.open behave like that when destroyed?
  • I tried running the iFrame source locally and the window open behaves properly even after refreshing.
  • I tried in IE, Firefox, and Chrome, and it returned the same behaviour.

UPDATE:

Mike successfully fixed the behavior for Webkit browsers by added sandbox properties for the iFrame source. Now the window.open method works as intended and not creating new instances of the same window of the same window.name.

However, Mike still has no luck with Firefox. If someone could give a work around for this, it would be much appreciated.

The Webkit browser behaviour for an iFrame with sanboxed properties in the video below.

See that the parent, even when refreshed still can detect that there is an already opened popup of the same name. https://youtu.be/z5_xXRjY8Ow

The Firefox behaviour for an iFrame with sanboxed properties in the video below.

When the parent window is refreshed, the browser could not detect the already opened popup and creates another instance of the pop up with the same window.name. https://youtu.be/uHaDveW1Sd0

Is there a workaround to make Firefox behave like Webkit browsers?

UPDATE:

Mike found out that using a blank url in window.open behave properly in firefox. But still how to fix this haha.

UPDATE:

Here's Johnny! er Mike means another test case. Try using webkit browsers and firefox. After opening a popup, refresh the page then open another popup webkit browsers will only have one instance of thy window, however firefox will create a new one. console.log(window.name) on the opened popup window and you shall get 'Mike' as the window name https://bug1295839.bmoattachments.org/attachment.cgi?id=8782242

1 Answers

Answers 1

There are several problems that I see in your code:

  1. You are calling a function that are nested inside another function to close the window, that never gets triggered because parent function is not callable at this time.

    function openWin(){      /* code */ } function closeWin(){      /* code */ } 
  2. To insure browser compatibility to close the Window, I strongly suggest to set and call an injectable function inside generated popup from parent window

Example to inject a function:

myWindow.document.write(         "<p>This is 'myWindow'</p>"         +"<script>"         +"function closeWindow()\{" // sample injected function         +"window.close();"         +"\}<\/script>"     );  

Full Example:

<!DOCTYPE html> <html> <body>   <button onclick="openWin()">Open "myWindow"</button> <button onclick="closeWin()">Close "myWindow"</button>  <script>  var myWindow; function openWin() {     myWindow = window.open("", "myWindow", "width=200,height=100");     myWindow.document.write(         "<p>This is 'myWindow'</p>"         +"<script>"         +"function closeWindow()\{" // sample injected function         +"window.close();"         +"\}<\/script>"     );     } function closeWin() {         if(!myWindow.closeWindow) {             setTimeout(closeWin,1000); // repeat if function not found         } else {              myWindow.closeWindow();         } } </script> </body> </html> 
Read More

How to keep “new solution explorer views” after reload a project in Visual Studio 2015?

Leave a Comment

Every time I load my project I do organize my workspace into 3 "new solution explorer view". One Solution Explorer for the views folder, one for the models folder and the last one for the controllers folder.

However when I close and reopen my project it is set back to the default workspace. Is possible to keep those created solution explorer views ?

The Save workspace option don't work with multiples solutions explorers.

1 Answers

Answers 1

Unfortunately, the short answer is "you can't". I have been attempting to find a solution utilising the MS Macro addin, and some of the other tools available, but none of them seems to be able to automate the opening of additional solution views, let alone a way of persisting them once they are set up.

I was quite surprised that the "Save Window Layout" feature in VS2015 doesn't allow you to do this either. It simply ignores any additional solution views. My theory on this is that, as the views are solution specific, it doesn't make sense to have them persisted as a default for the entire environment.

Read More

Can't import LDAP query feed data

Leave a Comment

I've set up an LDAP query that successfully pulls all data from the field physicaldeliveryofficename from our Windows Active Directory:

LDAP_query.png

I also setup a View that uses the query to further refine the list, so I am confident that the query itself is working:

LDAP_views.png

The problem occurs when I try to use Feeds Importers to grab that data and add it to my Offices content type. Here are my settings:

Basic settings

Name: Offices Attach to content type: Use standalone form Periodic import: 1 day Import on submission: checked

Fecher

LDAP Query Fetcher is selected

LDAP Query Fetcher

LDAP Query: HPSI Offices (that's the right query)

Parser

LDAP Entry Parser for Feeds is selected

Processor

Node processor is selected

Node processor

Bundle: Office Language: Language neutral Insert new nodes: Insert new nodes Update existing nodes: Update existing nodes Text format: plain text (also tried HTML) Action to take when previously imported nodes are missing in the feed: Delete non-existent nodes Author: Currently using user 1, but also tried anonymous Authorize: checked Expire nodes: never

Mapping

Source: [physicaldeliveryofficename] Target: Title (title) Used as unique

When I run this feed importer, the only thing that happens is a single Office is created with a blank title (see last image.) Can anyone tell me why this importer isn't working when both the LDAP query and a View that depends on it are working?

Feeds_import.png

UPDATE: I opened an issue against LDAP Feeds at Drupal.org and it appears I'm not the only one with this problem. https://www.drupal.org/node/2685009

1 Answers

Answers 1

Sounds a great deal like the issue reported on the LDAP module's issue queue. Try applying the patch from comment 11.

Read More

hive auto increment after certain number

Leave a Comment

I have a to insert data into a target table where all columns should be populated from different source tables except the surrogate key column; which should be maximum value of the target table plus auto increment value starting 1. I can generate auto increment value by using row_number() function, but in the same query how should I get the max value of surrogate key from target table. Is there any concept in HIVE where I can select the max value of surrogate key and save it in a temporary variable? Or is there any other simple way to achieve this result?

1 Answers

Answers 1

Here are two approaches which worked for me for the above problem. ( explained with example)

Approach 1: getting the max and setting to hive commands through ${hiveconf} variable using shell script

Approach 2: using row_sequence(), max() and join operations

My Environment:

hadoop-2.6.0 apache-hive-2.0.0-bin 

Steps: (note: step 1 and step 2 are common for both approaches. Starting from step 3 , it differs for both)

Step 1: create source and target tables

source

hive>create table source_table1(string name); hive>create table source_table2(string name); hive>create table source_table2(string name); 

target

hive>create table target_table(int id,string name); 

Step 2: load data into source tables

hive>load data local inpath 'source_table1.txt' into table source_table1; hive>load data local inpath 'source_table2.txt' into table source_table2; hive>load data local inpath 'source_table3.txt' into table source_table3; 

Sample Input:

source_table1.txt

a b c 

source_table2.txt

d e f 

source_table3.txt

g h i 

Approach 1:

Step 3: create a shell script hive_auto_increment.sh

#!/bin/sh hive -e 'select max(id) from target_table' > max.txt wait value=`cat max.txt` hive --hiveconf mx=$value -e "add jar /home/apache-hive-2.0.0-bin/lib/hive-contrib-2.0.0.jar; create temporary function row_sequence as 'org.apache.hadoop.hive.contrib.udf.UDFRowSequence'; set mx; set hiveconf:mx; INSERT INTO TABLE target_table SELECT row_sequence(),name from source_table1; INSERT INTO TABLE target_table SELECT (\${hiveconf:mx} +row_sequence()),name from source_table2; INSERT INTO TABLE target_table SELECT (\${hiveconf:mx} +row_sequence()),name from source_table3;" wait hive -e "select * from target_table;" 

Step 4: run the shell script

 > bash  hive_auto_increment.sh  

Approach 2:

Step 3: Add Jar

    hive>add jar /home/apache-hive-2.0.0-bin/lib/hive-contrib-2.0.0.jar; 

Step 4: register row_sequence function with help of hive contrib jar

hive>create temporary function row_sequence as 'org.apache.hadoop.hive.contrib.udf.UDFRowSequence'; 

Step 5: load the source_table1 to target_table

hive>INSERT INTO TABLE target_table select row_sequence(),name from source_table1; 

Step 6: load the other sources to target_table

  hive>INSERT INTO TABLE target_table SELECT M.rowcount+row_sequence(),T.name from source_table2 T join (select max(id) as rowcount from target_table) M;    hive>INSERT INTO TABLE target_table SELECT  M.rowcount+row_sequence(),T.name from source_table3 T join (select max(id) as rowcount from target_table) M; 

output:

INFO  : OK +---------------+-----------------+--+ | target_table.id  | target_table.name   +---------------+-----------------+--+ | 1                | a               | | 2                | b               | | 3                | c               | | 4                | d               | | 5                | e               | | 6                | f               | | 7                | g               | | 8                | h               | | 9                | i               | 
Read More

Rewriterule .htaccess in subfolder

Leave a Comment

I need to perform a rewrite in a subfolder using the .htaccess file. The current url has a form like:

domain.com/subfolder/chapter.php?urlkey=name 

It needs to be rewritten to:

domain.com/subfolder/chapter/name 

In the subfolder I have a .htaccess file with the following code:

<IfModule mod_rewrite.c>     Options -Indexes     RewriteEngine On     RewriteBase /subfolder/      RewriteCond %{REQUEST_FILENAME} !-d      RewriteCond %{REQUEST_FILENAME}\.php -f      RewriteRule ^chapter/([a-z0-9]+)/?$ chapter.php?urlkey=$1 [L,NC,QSA] </IfModule> 

Modrewrite is enabled, but for some reason when I go to the url

domain.com/subfolder/chapter/name 

It returns the following error:

Notice: Undefined index: urlkey 

3 Answers

Answers 1

Have this code in subfolder/.htaccess:

Options -MultiViews RewriteEngine On RewriteBase /subfolder/  RewriteRule ^chapter/([\w-]+)/?$ chapter.php?urlkey=$1 [L,NC,QSA] 

Option MultiViews (see http://httpd.apache.org/docs/2.4/content-negotiation.html) is used by Apache's content negotiation module that runs before mod_rewrite and makes Apache server match extensions of files. So if /file is the URL then Apache will serve /file.html.

Also there is no need to rewrite to chapter?... you can rewrite to chapter.php?...

Answers 2

Your error is not related to htaccess rules.

Notice: Undefined Index

Happens when you try to access an array by a key that does not exist in the array.

A typical example for an Undefined Index notice would be check sample code below.

$data = array('foo' => '42', 'bar'); echo $data['spinach']; echo $data[1]; 

Both spinach and 1 do not exist in the array, causing an to be triggered.

The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_exists or isset:

$data = array('foo' => '42', 'bar'); if (array_key_exists('spinach', $data)) {     echo $data['spinach']; } else {     echo 'No key spinach in array'; } 

If you have code like:

<?php echo $_POST['message']; ?> <form method="post" action="">     <input type="text" name="message">     ... 

then $_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:

if ($_POST)  ..  // if the $_POST array is not empty // or if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST 

The notices above appear often when working with $_POST, $_GET or $_SESSION. For $_POST and $_GET you just have to check if the index exists or not before you use them. For $_SESSION you have to make sure you have the session started with session_start() and that the index also exists.

Answers 3

When removing RewriteBase it does working for me

put this in subfolder please check

Options -Indexes RewriteEngine On  RewriteCond %{REQUEST_FILENAME} !-d  RewriteCond %{REQUEST_FILENAME}\.php -f  RewriteRule ^chapter/([a-z0-9]+)/?$ chapter.php?url=$1 [L,NC,QSA] 

and you have to add chapter.php? instead of chapter?.

Read More