input
stringlengths
51
42.3k
output
stringlengths
18
55k
jqGrid 4.12 border disappearing in all browsers <p><a href="https://staging.transporthub.co.uk/gridtest/jqgrid.htm" rel="nofollow">https://staging.transporthub.co.uk/gridtest/jqgrid.htm</a> </p> <p>When clicking in the cell to edit the value the border at the right and bottom is disappearing. Is there a css issue?</p>
<p>First of all, please, don't use old versions of <a href="https://github.com/free-jqgrid/jqGrid" rel="nofollow">free jqGrid</a>. The current version of free jqGrid is 4.13.4. I recommend you to change the URLs to CDN (see <a href="https://github.com/free-jqgrid/jqGrid/wiki/Access-free-jqGrid-from-different-CDNs" rel="nofollow">the wiki</a>).</p> <p>The reason of your problem is not depend from the choice of the version. Your demo contains the following customization:</p> <pre class="lang-css prettyprint-override"><code>.ui-state-highlight { border:none!important; /* !!! it's the origin of your problem */ background:none!important; } </code></pre> <p>which is the origin of your problem. You use cell editing (<code>cellEdit: true</code>), which selects (set <code>ui-state-highlight</code> class) non-editable cells during editing. The usage <code>border:none!important;</code> in the above CSS rule removes the border of the cell. You should remove the CSS rule.</p>
setOnAction within another setOnAction not working for arrays of buttons in Javafx <p>I'm actually not sure about the title because I don't know if that is the real problem. I'm making this application that the user clicks on a plus or minus button to get a number of people, then for each person there are two more plus and minus buttons to get another number that has to be multiplied by 15 and the result is shown in a TextField. i don't know why my code is giving me this error: "Local variable i defined in an enclosing scope must be final or effectively final". I commented the code where the error is shown.</p> <p>Any help would be very appreciated.</p> <p>Thanks very much. </p> <pre><code>int arrayLength; int counter = 1; double bc = 15.00; Button[] baggagePlus; Button[] baggageMinus; Label[] baggageCounter; Label[] costBaggage; CheckBox[] checkReturn; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { stage = primaryStage; stage.setTitle(""); stage.setResizable(false); pane = new BorderPane(); pane.setStyle("-fx-background: #CEF6D8;"); centerPane1 = new Pane(); GridPane mainGrid = new GridPane(); mainGrid.setPadding(new Insets(150, 0, 0, 100)); mainGrid.setVgap(50); noPassGrid = new GridPane(); noPassGrid.setHgap(10); adultPlus = new Button("+"); adultPlus.setMinWidth(50); adultPlus.setFont(Font.font("Verdana", 20)); GridPane.setConstraints(adultPlus, 1, 0); adultPlus.setOnAction(e -&gt; { plus(adultCounter); getArraySize(); }); adultCounter = new Label("1"); adultCounter.setFont(Font.font("Verdana", 20)); GridPane.setConstraints(adultCounter, 2, 0); adultMinus = new Button("-"); adultMinus.setMinWidth(50); adultMinus.setFont(Font.font("Verdana", 20)); GridPane.setConstraints(adultMinus, 3, 0); adultMinus.setOnAction(e -&gt; { minus(adultCounter); getArraySize(); }); noPassGrid.getChildren().addAll(adultPlus, adultCounter, adultMinus); GridPane.setConstraints(noPassGrid, 0, 2); mainGrid.getChildren().addAll(noPassGrid); search = new Button("SEARCH"); search.setPrefSize(300, 100); search.setFont(new Font("Verdana", 30)); passengersGrid = new GridPane(); search.setOnAction(e -&gt; { passengersGrid.setPadding(new Insets(150, 0, 0, 450)); passengersGrid.setVgap(20); passengersGrid.setHgap(20); for(int i=0; i&lt;arrayLength; i++) { baggagePlus[i] = new Button("+"); baggagePlus[i].setMinWidth(50); baggagePlus[i].setFont(Font.font("Verdana", 20)); GridPane.setConstraints(baggagePlus[i], 5, i); baggageCounter[i] = new Label("0"); baggageCounter[i].setFont(Font.font("Verdana", 20)); GridPane.setConstraints(baggageCounter[i], 6, i); baggagePlus[i].setOnAction( new EventHandler&lt;ActionEvent&gt;() { public void handle(ActionEvent e) { plus(baggageCounter[i]); //The "i" is underlined showing error doublePrice(checkReturn[i], costBaggage[i], bc, baggageCounter[i]); } }); baggageMinus[i] = new Button("-"); baggageMinus[i].setMinWidth(50); baggageMinus[i].setFont(Font.font("Verdana", 20)); GridPane.setConstraints(baggageMinus[i], 7, i); baggageMinus[i].setOnAction( new EventHandler&lt;ActionEvent&gt;() { public void handle(ActionEvent e) { minus(baggageCounter[i]); //The "i" is underlined showing error doublePrice(checkReturn[i], costBaggage[i], bc, baggageCounter[i]); } }); checkReturn[i] = new CheckBox(); checkReturn[i].setFont(Font.font(20)); GridPane.setConstraints(checkReturn[i], 10, i); checkReturn[i].setOnAction(new EventHandler&lt;ActionEvent&gt;() { public void handle(ActionEvent e) { //The "i" is underlined showing error doublePrice(checkReturn[i], costBaggage[i], bc, baggageCounter[i]); } }); costBaggage[i] = new Label("€0.00"); costBaggage[i].setFont(Font.font("Verdana", 25)); GridPane.setConstraints(costBaggage[i], 18, i); passengersGrid.getChildren().addAll(baggagePlus[i], baggageCounter[i], baggageMinus[i], checkReturn[i], costBaggage[i]); } }); centerPane1.getChildren().addAll(mainGrid, passengersGrid); pane.setCenter(centerPane1); bottom1 = new AnchorPane(search); bottom1.setPadding(new Insets(0, 0, 100, 0)); AnchorPane.setRightAnchor(search, 150.0); pane.setBottom(bottom1); scene = new Scene(pane, 1200, 600); stage.setScene(scene); stage.show(); } public void getArraySize() { arrayLength = counter; baggagePlus = new Button[arrayLength]; baggageMinus = new Button[arrayLength]; baggageCounter = new Label[arrayLength]; costBaggage = new Label[arrayLength]; checkReturn = new CheckBox[arrayLength]; } public void plus(Label l) { if(counter &lt; 8) { counter++; l.setText("" + counter); } } public void minus(Label l) { if(counter &gt; 1) { counter--; l.setText("" + counter); } } public void doublePrice(CheckBox cb, Label ll, double bc, Label l) { if(cb.isSelected()) { ll.setText("€" + df.format(2 * bc * (Double.parseDouble(l.getText())))); } else { ll.setText("€" + df.format(bc * (Double.parseDouble(l.getText())))); } } } </code></pre>
<p>The error is exactly what it says: i must be final (or effectively final, meaning that compiler must be able to deduce that the variable will never change.</p> <p>In your case, <code>i</code> changes (between 0 and 10), so it's not "effectively final".</p> <p>What you want to do is add a variable to hold the current snapshot of <code>i</code> and store it in a final variable; for example on the top of the loop add:</p> <pre><code>final int snapshot = i; </code></pre> <p>If you think about it, this Java behavior is very logical - by the time any of the listeners fire, the loop in question is over, so there is no such thing as <em>current value of i</em>. Instead, there's a <em>snapshot of i value taken during the iteration when the listener was established</em>.</p>
Allow multiple controllers to users according to their role in cakephp <p>Suppose, there are two roles: one is <code>admin</code>, another is <code>restaurant_owner</code>.</p> <p>I want to give access to some of the pages to <code>restaurant_owner</code>.</p> <p>In <code>AppController</code>, I used <code>beforeFilter</code> function. Here is the code..</p> <pre><code>public function beforeFilter() { if($this-&gt;Auth-&gt;user('role') == 'restaurant_owner'){ /* Controllers Name, that Admin want to give access to restaurant admin*/ $this-&gt;loadModel('Userpermission'); $AuthPermission = $this-&gt;Userpermission-&gt;find('first',array('conditions' =&gt; array('Userpermission.user_id' =&gt; $this-&gt;Auth-&gt;user('id')))); print_r($AuthPermission); //returns controller names e.g. receipes, menuitems } } </code></pre> <p>My question is, how I deny access to role <code>restaurant_owner</code> to all controllers except but a few? I'm using CakePHP 2.x.</p>
<p>The proper way of handling this is through <a href="http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#using-controllerauthorize" rel="nofollow"><code>ControllerAuthorize</code></a> and the <code>AuthComponent::isAuthorized()</code> callback.</p> <p>First, you have to enable this functionality in <code>AppController</code>. Edit your <code>Auth</code> config and array and add the following:</p> <pre><code>public $components = array( 'Auth' =&gt; array('authorize' =&gt; 'Controller'), ); </code></pre> <p>Then add the following to the controllers which <code>restaurant_owner</code> should have access to:</p> <pre><code>public function isAuthorized($user) { if ($user['role']=="restaurant_owner") { return true; } return parent::isAuthorized($user); } </code></pre> <p>Finally, add the following to <code>AppController</code>:</p> <pre><code>public function isAuthorized($user) { if ($user['role']=="restaurant_owner") { return false; } return true; //Every other role is authorized } </code></pre> <p>You will have to tweak the above logic to match your needs.</p>
How to add object in an array of objects using Javascript <p>I have the below JS object and I need to push another similar object with <code>request.rules[0]</code>.</p> <pre><code>request : [ rules: [ { pageFilters: [ { matchType: 'contains', type: 1, value: 'a' }, { matchType: 'does not contain', type: 1, value: 'b' } ], name: 'TEST' } ] ] </code></pre> <p>This is the object that I need to push to request.rules[1]:</p> <pre><code>{ pageFilters: [ { matchType: 'contains', type: 1, value: 'c' }, { matchType: 'does not contain', type: 1, value: 'd' } ], name: 'TEST 2' } </code></pre> <p>This is what I've tried to implement, but it does not work ...</p> <pre><code>request.rules[1].pageFilters[0].push({ matchType: 'contains', type: 1, value: 'c' }) request.rules[1].pageFilters[1].push({ matchType: 'contains', type: 1, value: 'd' }) request.rules[1].name = "TEST 2"; </code></pre> <p>This is the expected result:</p> <pre><code>request :[ rules: [ { pageFilters: [ { matchType: 'contains', type: 1, value: 'a' }, { matchType: 'does not contain', type: 1, value: 'b' } ], name: 'TEST' }, { pageFilters: [ { matchType: 'contains', type: 1, value: 'c' }, { matchType: 'does not contain', type: 1, value: 'd' } ], name: 'TEST 2' } ] ] </code></pre>
<p>You do not have to push to a specific position e.g request.rules[1].pageFilters[0], but rather to the array itself like this</p> <pre><code>var anotherFilter = { matchType=contains, type=1, value=c }; request.rules[1].pageFilters.push(anotherFilter); </code></pre>
Validate URL in Swift 3 <p>I am trying to validate an URL in Swift 3 but I can't seem to find the Regex that suits my needs. Regex that I am after needs to accept following combinations:</p> <pre><code>http://google.com http://google.com/foo/bar:30/35 https://google.com https://google.com/foo/bar:30/35 www.google.com google.com </code></pre>
<pre><code>func validateUrl (urlString: NSString) -&gt; Bool { let urlRegEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?&lt;=/)(?:[\\w\\d\\-./_]+)?)?" return NSPredicate(format: "SELF MATCHES %@", urlRegEx).evaluateWithObject(urlString) } </code></pre> <p>This worked.</p>
How to call a non-activity method on Notification Click <p>I have a java class <code>MyClass</code> which contains a method called <code>callMethod</code>. I want to call this method when user clicks on the notification</p> <p>Below is the code i used to generate the notification</p> <pre><code>public class MainActivity extends AppCompatActivity { Button button; NotificationManager mNotifyMgr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); mNotifyMgr = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this, MyClass.class), PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new NotificationCompat.Builder(MainActivity.this) .setContentTitle("Notification") .setSmallIcon(R.drawable.ic_launcher) .setContentText("Downloaded") .setContentIntent(pendingIntent) .build(); mNotifyMgr.notify(1,notification); } }); } } </code></pre> <p>And below is the implementation of <code>MyClass</code></p> <pre><code>public class MyClass { public void callMethod(){ System.out.println("Notification clicked"); } } </code></pre> <p>Please help, I am stuck into this for a while now</p>
<pre><code> @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); //notification callbacks here in activity //Call method here from non activity class. Classname.methodName(); } </code></pre>
sessionStorage doesnt work on safari on iphone 6 - non private mode <p>If i use the following code below, it works perfectly on firefox (private window or normal window). I tried to use it on my iphone 6 using safari and it doesnt seem to store my information in normal mode (non private mode)? Maybe the code is not right for safari? Can someone assist me? Thanks!</p> <p>Code:</p> <pre><code>&lt;script&gt; // Run on page load window.onload = function() { // If sessionStorage is storing default values (ex. name), exit the function and do not restore data if (sessionStorage.getItem('name') == "name") { return; } // If values are not blank, restore them to the fields var name = sessionStorage.getItem('name'); if (name !== null) $('#playlisthiddenfield').val(name); } // Before refreshing the page, save the form data to sessionStorage window.onbeforeunload = function() { sessionStorage.setItem("name", $('#playlisthiddenfield').val()); } &lt;/script&gt; </code></pre> <p>Basically the issue is, once i refresh the information in the input field disappears where as in firefox it stays (Which i want it to).</p>
<p>I dont exactly have the answer to the question but instead i decided to use cookies to complete this task and i am only storing a value which i can access with an if statement so no personal information is stored.</p>
F# Sort an Array with foldBack or fold. <p>I am trying to sort an Array by using fold or foldBack. </p> <p>I have tried achieving this like this: </p> <pre><code>let arraySort anArray = Array.fold (fun acc elem -&gt; if acc &gt;= elem then acc.append elem else elem.append acc) [||] anArray </code></pre> <p>this ofcourse errors horribly. If this was a list then i would know how to achieve this through a recursive function but it is not. </p> <p>So if anyone could enlighten me on how a workable function given to the fold or foldback could look like then i would be createful. </p> <p>Before you start advising using <code>Array.sort anArray</code> then this wont do since this is a School assignment and therefore not allowed. </p>
<h3>To answer the question</h3> <p>We can use <code>Array.fold</code> for a simple insertion sort-like algorithm:</p> <pre><code>let sort array = let insert array x = let lesser, greater = Array.partition (fun y -&gt; y &lt; x) array [| yield! lesser; yield x; yield! greater |] Array.fold insert [||] array </code></pre> <p>I think this was closest to what you were attempting.</p> <hr> <h3>A little exposition</h3> <p>Your comment that you have to return a sorted version of the same array are a little confusing here - F# is immutable by default, so <code>Array.fold</code> used in this manner will actually create a new array, leaving the original untouched. This is much the same as if you'd converted it to a list, sorted it, then converted back. In F# the array type is immutable, but the elements of an array are all mutable. That means you can do a true in-place sort (for example by the library function <code>Array.sortInPlace</code>), but we don't often do that in F#, in favour of the default <code>Array.sort</code>, which returns a new array.</p> <p>You have a couple of problems with your attempt, which is why you're getting a few errors.</p> <p>First, the operation to append an array is very different to what you attempted. We could use the <code>yield</code> syntax to append to an array by <code>[| yield! array ; yield element |]</code>, where we use <code>yield!</code> if it is an array (or in fact, any <code>IEnumerable</code>), and <code>yield</code> if it is a single element.</p> <p>Second, you can't compare an array type to an element of the array. That's a type error, because <code>compare</code> needs two arguments of the same type, and you're trying to give it a <code>'T</code> and a <code>'T array</code>. They can't be the same type, or it'd be infinite (<code>'T = 'T array</code> so <code>'T array = 'T array array</code> and so on). You need to work out what you should be comparing instead.</p> <p>Third, even if you could compare the array to an element, you have a logic problem. Your element either goes right at the end, or right at the beginning. What if it is greater than the first element, but less than the last element?</p> <p>As a final point, you can still use recursion and pattern matching on arrays, it's just not quite as neat as it is on lists because you can't do the classic <code>| head :: tail -&gt;</code> trick. Here's a basic (not-so-)quicksort implementation in that vein.</p> <pre><code>let rec qsort = function | [||] -&gt; [||] | arr -&gt; let pivot = Array.head arr let less, more = Array.partition (fun x -&gt; x &lt; pivot) (Array.tail arr) [| yield! qsort less ; yield pivot ; yield! qsort more |] </code></pre> <p>The speed here is probably several orders of magnitude slower than <code>Array.sort</code> because we have to create many many arrays while doing it in this manner, which .NET's <code>Array.Sort()</code> method does not.</p>
How to add event to my CustomCell in Swift3 <p>I have a UITableView which has rows which include two UISwitch buttons. Until I upgraded to Xcode8 it worked with me adding a protocol to the view controller like this</p> <pre><code>protocol CustomCellDelegator { func callSegueFromCell() } </code></pre> <p>Then I added the following to my CustomCell swift file which handles the outlets for my custom cell.</p> <pre><code>open class CustomTableViewCell: UITableViewCell { var delegate:CustomCellDelegator! @IBOutlet weak var uidLabel: UILabel! @IBOutlet weak var stateLabel: UILabel! @IBOutlet weak var operatedSwitch: UISwitch! @IBOutlet weak var switchRTN: UISwitch! override open func awakeFromNib() { super.awakeFromNib() // Initialization code } @IBAction func operatedSwitchChange() { if operatedSwitch.isOn { AppDelegate.myGlobalVars.gSwitchType = "OpsOn" } else { AppDelegate.myGlobalVars.gSwitchType = "OpsOff" } if(self.delegate != nil){ //Just to be safe. self.delegate.callSegueFromCell() } } @IBAction func rtnSwitchChange() { if switchRTN.isOn { AppDelegate.myGlobalVars.gSwitchType = "RtnOn" } else { AppDelegate.myGlobalVars.gSwitchType = "RtnOff" } if(self.delegate != nil){ //Just to be safe. self.delegate.callSegueFromCell() } } } </code></pre> <p>Until I upgraded this worked and delegate always had a value, now it is always nil and the segue is never called.</p> <p>What do i need to do differently since I upgraded to get this working again? </p>
<p>Make sure You assign your delegate in <code>cellForRowAtIndexPath</code> for the cell. Also, I would recommend to keep <code>weak</code> reference to the delegate.</p> <pre><code>protocol CustomCellDelegator: class { func callSegueFromCell() } </code></pre> <p>In your <code>CustomTableViewCell</code> replace </p> <pre><code>var delegate:CustomCellDelegator! </code></pre> <p>with </p> <pre><code>weak var delegate: CustomCellDelegator? </code></pre> <p>After this you do not need to check if Your delegate is <code>nil</code> or not, your app will not crash.</p>
dynamically checking existing cd rom letter and change it to Z in powershell <pre><code>Set-WmiInstance -InputObject ( Get-WmiObject -Class Win32_volume -Filter "DriveLetter = 'd:'" ) -Arguments @{DriveLetter='Z:'} </code></pre> <p>This script will check for cd rom letter and change it to Z .. but only if cd rom letter is D. how abt dynamically checking existing cd rom letter</p>
<p>There is a <code>Win32_CDROMDrive</code> WmiObject which you can use to determine the existing CDROM drive letter:</p> <pre><code>$letter = Get-WmiObject -Class Win32_CDROMDrive | select -ExpandProperty Drive Set-WmiInstance -InputObject ( Get-WmiObject -Class Win32_volume -Filter "DriveLetter = '$letter'" ) -Arguments @{DriveLetter='Z:'} </code></pre>
Scala implicit macros: Filter type members (tpe.decls) by sub-type <p>Let's say I have a simple impicit macro that gives me back a <code>weakTypeSymbol</code>:</p> <pre><code>@macrocompat.bundle class ExampleMacro(val c: blackbox.Context) { def macroImpl[T : WeakTypeTag]: Tree = { val tpe = weakTypeOf[T] val subType = typeOf[SomeType].typeSymbol val target = tpe.decls.collect { case tp if tp.typeSignature.typeSymbol == subType =&gt; tp } ... } } </code></pre> <p>That's a very rudimentary version of it, in short I need inner members of <code>T</code> that satisfy a particular sub-typing relationship. It looks like the types on the inner members however have not been evaluated at this time, because <code>tp.typeSignature.typeSymbol</code> is <code>&lt;none&gt;</code>.</p> <p>Is there a known way of doing this properly?</p>
<p>This is doable with an API similar to reflection:</p> <pre><code> class TestMacro(val c: blackbox.Context) { import c.universe._ def filterMembers[ T : WeakTypeTag, Filter : TypeTag ]: List[Symbol] = { val tpe = weakTypeOf[T].typeSymbol.typeSignature (for { baseClass &lt;- tpe.baseClasses.reverse symbol &lt;- baseClass.typeSignature.members.sorted if symbol.typeSignature &lt;:&lt; typeOf[Filter] } yield symbol)(collection.breakOut) } } </code></pre>
Verify private static method on final class gets called using PowerMockito <p>I have the following class</p> <pre><code>public final class Foo { private Foo() {} public static void bar() { if(baz("a", "b", new Object())) { } } private static boolean baz(Object... args) { return true; // slightly abbreviated logic } } </code></pre> <p>And this is my Test:</p> <pre><code>@PrepareOnlyThisForTest(Foo.class) @RunWith(PowerMockRunner.class) public class FooTest { @Test public void bar() { PowerMockito.mockStatic(Foo.class); // prepare Foo.bar(); // execute verifyPrivate(Foo.class, times(1)).invoke("baz", anyVararg()); // verify - fails } } </code></pre> <p>For that, I get the following error message - and I don't understand why...</p> <blockquote> <p>Wanted but not invoked com.example.Foo.baz( null );</p> <p>However, there were other interactions with this mock.</p> </blockquote> <p>Removing the <code>prepare</code> line above seems to make the verify line pass no matter for how many <code>times</code> you check for... :(</p> <p>(Our SONAR code checks enforce that each test has some sort of <code>assertXyz()</code> in it (hence the call to <code>verify()</code>) and enforces a very high test coverage.)</p> <p>Any ideas how to do this?</p>
<p>The problem with your code is that you <strong>mock</strong> <code>Foo</code> so your method implementations won't be called by default such that when you call <code>Foo.call()</code> it does nothing by default which means that it never avtually calls <code>baz</code> that is why you get this behavior. If you want to <strong>partially mock</strong> <code>Foo</code>, mock it using the option <code>Mockito.CALLS_REAL_METHODS</code> in order to make it call the real methods as you seem to expect, so the code should be:</p> <pre><code>@PrepareOnlyThisForTest(Foo.class) @RunWith(PowerMockRunner.class) public class FooTest { @Test public void bar() throws Exception { PowerMockito.mockStatic(Foo.class, Mockito.CALLS_REAL_METHODS); // prepare ... } } </code></pre>
Oxyplot horizontal pan only between the leftmost and rightmost points <p>I'm using <code>Oxyplot</code> to show graphs. I added the horizontal Pan as following:</p> <pre><code>private void AddHorizonalPanToLinearModel(){ var b = false; GraphModel.MouseDown += (s, e) =&gt; { if (e.ChangedButton != OxyMouseButton.Left) return; b = true; CurrentMousePosition = e.Position; }; GraphModel.MouseMove += (s, e) =&gt; { _xLinearAxis.Pan(CurrentMousePosition, e.Position); CurrentMousePosition = e.Position; GraphModel.InvalidatePlot(false); e.Handled = true; }; GraphModel.MouseUp += (s, e) =&gt; b = false; } </code></pre> <p>I'm looking for a solution that limits the pan between the leftmost and rightmost x-values but I can't find anything. Have you got any ideas?</p>
<p>As explained <a href="http://stackoverflow.com/questions/31430752/oxyplotcannot-setting-axis-values">here</a> the solution is to set <code>AbsoluteMinimum</code> and <code>AbsoluteMaximum</code> of the axis.</p>
How do I get the first element of a dynamic/generic type <p>Is there any way to pass in a generic entity object and get the first in its query.</p> <p>My intention is to call <code>FirstOrDefault()</code> on every table, and try catch for errors in the databases integrity.</p> <p>It would have been nicer to be able to call it by string parameter e.g. <code>db.Entity("myTable").FirstOrDefault()</code> but such a method doesn't seem to exist.</p> <p>Below is some generic <code>T</code> attempt, but i get the object not set to instance error.</p> <pre><code> // Called with //GetFirstObject&lt;myTable&gt;(db.myTable); public static void GetFirstObject&lt;T&gt;(object obj) { MethodInfo method = typeof(IEnumerable&lt;T&gt;).GetMethod("FirstOrDefault"); MethodInfo generic = method.MakeGenericMethod(); generic.Invoke(obj, null); } </code></pre>
<p>Why not use <code>Set&lt;T&gt;()</code>?</p> <pre><code>public T GetFirstObject&lt;T&gt;() where T : class { return context.Set&lt;T&gt;().FirstOrDefault(); } </code></pre> <p>You can also pass <em>filter expression</em>:</p> <pre><code>public T GetFirstObject&lt;T&gt;(Expression&lt;Func&lt;T, bool&gt;&gt; filterExpression) where T : class { return context.Set&lt;T&gt;().FirstOrDefault(filterExpression); } </code></pre>
Regex in Node.js not showing all matches <p>To prepare a request-url for an API-call I am using RegEx to replace values from a String with values from an object. </p> <p>Example of a 'template-string':</p> <pre><code>'https://api.fitbit.com/1/user/:ownerId/:collectionType/date/:date.json' </code></pre> <p>where :ownerId, :collectionType and :date will be replaced by the values from the following object:</p> <pre><code>{ collectionType: 'activities', date: '2016-10-12', ownerId: 'xxxxx', ownerType: 'user', subscriptionId: 'xxx' } </code></pre> <p>The regular expression I am using is: </p> <pre><code>/:([\w]+)/gi </code></pre> <p>This allows me to use the content of the group in every match to fetch the value from the object. (the match without the ':' in this case) I have the following function to return the request-url: (url is the 'template-string' and decoded is the object above)</p> <pre><code>function regexifyUrlTemplate(url, regex, decoded) { console.log('Regexify URL: ', url) console.log('Regexify Data: ', decoded) var m while (( m = regex.exec(url)) !== null) { if (m.index === regex.lastIndex) { regex.lastIndex++ } console.log('Matches: ', m) url = String(url).replace(m[0], decoded[m[1]]) console.log('Replaced ' + m[0] + ' with ' + decoded[m[1]]) } console.log('Regexify :', url) return url } </code></pre> <p>The console shows me the following logs:</p> <pre><code>Regexify URL: https://api.fitbit.com/1/user/:ownerId/:collectionType/date/:date.json Regexify Data: { collectionType: 'activities', date: '2016-10-12', ownerId: 'xxx', ownerType: 'user', subscriptionId: 'xxx' } Matches: [ ':ownerId', 'ownerId', index: 31, input: '\'https://api.fitbit.com/1/user/:ownerId/:collectionType/date/:date.json\'' ] Replaced :ownerId with xxx Matches: [ ':date', 'date', index: 59, input: '\'https://api.fitbit.com/1/user/xxx/:collectionType/date/:date.json\'' ] Replaced :date with 2016-10-12 Regexify : 'https://api.fitbit.com/1/user/xxx/:collectionType/date/2016-10-12.json' </code></pre> <p>It successfully replaces :ownerId and :date but does not replace :collectionType. I verified the RegEx at <a href="https://regex101.com" rel="nofollow">regex101.com</a> and went through the regex with the updated strings from the logs. </p> <p>Can anyone explain why :collectionType is not being matched? The only difference I can spot is the 'T' but with [\w] that should not matter. (also tried [a-zA-Z]). </p>
<p>The problem was here <code>url = String(url).replace(m[0], decoded[m[1]])</code></p> <p>You modify <code>url</code> during the <code>exec()</code>, so matche's index change ...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var url = 'https://api.fitbit.com/1/user/:ownerId/:collectionType/date/:date.json'; var data = { collectionType: 'activities', date: '2016-10-12', ownerId: 'xxxxx', ownerType: 'user', subscriptionId: 'xxx' } var reg = /\:([\w]+)/gi; function regexifyUrlTemplate(url, regex, decoded) { console.log('Regexify URL: ', url) console.log('Regexify Data: ', decoded) var m, originUrl = url; while (( m = regex.exec(originUrl)) !== null) { //if (m.index === regex.lastIndex) { // regex.lastIndex++ //} console.log('Matches: ', m) url = String(url).replace(m[0], decoded[m[1]]) console.log('Replaced ' + m[0] + ' with ' + decoded[m[1]]) } console.log('Regexify :', url) return url } regexifyUrlTemplate(url, reg, data)</code></pre> </div> </div> </p>
Wordpress PHP shortcode, get_the_content by id won't display custom post type content <p>Currently working on a project where I want to display employees' business cards by a shortcode, for instance <code>[person id="1"]</code> or [<code>person name="bob"]</code>. </p> <p>I've created a seperate post type for employees, where title=name, content=contact info and thumbnail=image. </p> <p>The problem is that title and thumbnail shows the right employee data, but <code>get_the_content($post_id)</code> displays the content of my first post "Welcome to ...! This is your first post...".</p> <pre><code>function display_person($atts, $content){ extract(shortcode_atts(array( 'posts_per_page' =&gt; '1', 'post_type' =&gt; 'person', 'post_id' =&gt; null, 'caller_get_posts' =&gt; 1) , $atts)); global $post; $posts = new WP_Query($atts); $output = ''; if ($posts-&gt;have_posts()) while ($posts-&gt;have_posts()): $posts-&gt;the_post(); $out = '&lt;div class="col-lg-6 col-md-12 col-sm-12 col-xs-12"&gt; &lt;div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 person-container margin-top"&gt; &lt;div class="col-lg-6 col-md-6 col-sm-6 hidden-xs person-thumbnail no-padding"&gt; '.get_the_post_thumbnail($post_id, 'thumbnail-person').' &lt;/div&gt; &lt;div class="hidden-lg hidden-md hidden-sm col-xs-4 person-thumbnail no-padding"&gt; '.get_the_post_thumbnail($post_id, 'thumbnail-person-small').' &lt;/div&gt; &lt;div class="col-lg-6 col-md-6 col-sm-6 col-xs-8 person no-padding"&gt; &lt;h3&gt;'.get_the_title($post_id).'&lt;/h3&gt; '.get_the_content($post_id).' &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;'; $out .='&lt;/div&gt;'; endwhile; else return; wp_reset_query(); return html_entity_decode($out); } add_shortcode('person', 'display_person'); </code></pre> <p>How do I get <code>get_the_content($post_id)</code> to display the custom post content?</p>
<p>Your code seems a bit faulty.</p> <pre><code>// this is your shortcode extract(shortcode_atts(array( 'posts_per_page' =&gt; '1', 'post_type' =&gt; 'person', 'post_id' =&gt; null, 'caller_get_posts' =&gt; 1) , $atts)); </code></pre> <p>It should look like this (based on the assumption, that $atts' elements are taken from the shortcode parameters):</p> <pre><code>// you extract the parameters into variable names extract(shortcode_atts(array( 'posts_per_page' =&gt; 'posts_per_page_var', 'post_type' =&gt; 'post_type_var', 'post_id' =&gt; 'post_id_var', 'caller_get_posts' =&gt; 'caller_get_posts_var') , $atts)); // creating the array of arguments for the query $new_atts = array( 'posts_per_page' =&gt; $posts_per_page_var, 'post_type' =&gt; $post_type_var, 'post_id' =&gt; $post_id_var, 'caller_get_posts' =&gt; $caller_get_posts_var ); $posts = new WP_Query($new_atts); // and go on with your code... </code></pre> <p>It think this should solve your problem.</p> <p>Longer tutorial:</p> <p><a href="http://www.webdesignerdepot.com/2013/06/how-to-create-your-own-wordpress-shortcodes/" rel="nofollow">http://www.webdesignerdepot.com/2013/06/how-to-create-your-own-wordpress-shortcodes/</a></p>
Is drag-and-drop to open a file possible in VSCode? <p>I am wondering if something is wrong with my computer (or myself), because I can't seem to drag &amp; drop a file into Visual Studio Code to open it in the editor. Closing an opened folder first doesn't make a difference. VSCode always shows me the 'stop sign', in every spot I tried (the editor, the opened tab bar, an existing opened file, ...).</p> <p>Why does VSCode block this ?</p> <p>(I have experienced this in earlier versions as well. Currently on v1.6 on Windows 7.)</p>
<p>Searching for a solution, I stumbled on <a href="https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/72f35f33-2df0-47e8-a16d-006f1190d81e/drag-and-drop-brokendisabled-when-running-as-an-administrator-?forum=windowsgeneraldevelopmentissues" rel="nofollow">this page</a>, where one commenter explains:</p> <blockquote> <p>I think you are running into the security issue where lower permission processes cannot send messages to higher permission processes. Explorere.exe, running at normal permission levels, cannot send the window message to winword.exe, running elevated. </p> </blockquote> <p>I am indeed always running VSCode as Administrator, but not my Explorer windows. </p> <p><strong>When I run VSCode in non-administrator mode (so just my regular user), drag-and-drop works fine.</strong></p>
Unit test Angular 2 error: Bootstrap at least one component before injecting Router? <p>I am writing test for component in angular 2 and I see a problem as below:</p> <p><a href="https://i.stack.imgur.com/trinn.png" rel="nofollow"><img src="https://i.stack.imgur.com/trinn.png" alt="enter image description here"></a></p> <p>Any help, thank you.</p>
<p>You need to use the <a href="https://angular.io/docs/ts/latest/api/router/testing/index/RouterTestingModule-class.html" rel="nofollow"><code>RouterTestingModule</code></a> instead of the <code>RouterModule</code> when testing. If you only need the directives, you can just import it as is</p> <pre><code>imports: [ RouterTestingModule ] </code></pre> <p>If you want to configure routes than you can call <code>withRoutes</code></p> <pre><code>imports: [ RouterTestingModule.withRoutes(ROUTES) ] </code></pre>
Laravel 5.3 - TokenMismatchException in VerifyCsrfToken.php line 68: <p>When I log in to my app, and immediately go back when I enter it, and then try to log out, I get the error from the title, how can I fix that?</p>
<p>From Laravel 5.3 docs </p> <blockquote> <p>The Auth::routes method now registers a POST route for /logout instead of a GET route. This prevents other web applications from logging your users out of your application. To upgrade, you should either convert your logout requests to use the POST verb or register your own GET route for the /logout URI:</p> </blockquote> <p><strong>Option One:</strong> <code>Route::get('/logout', 'Auth\LoginController@logout');</code></p> <p>For more about upgrade please have a look at this <a href="https://laravel.com/docs/5.3/upgrade" rel="nofollow">https://laravel.com/docs/5.3/upgrade</a></p> <p><strong>Option 2</strong></p> <pre><code>//Insert this on your head section &lt;!-- CSRF Token --&gt; &lt;meta name="csrf-token" content="{{ csrf_token() }}"&gt; &lt;!-- Scripts --&gt; &lt;script&gt; window.Laravel = &lt;?php echo json_encode([ 'csrfToken' =&gt; csrf_token(), ]); ?&gt; &lt;/script&gt; </code></pre> <p>Where you want you logout </p> <pre><code> &lt;ul class="dropdown-menu" role="menu"&gt; &lt;li&gt; &lt;a href="{{ url('/logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"&gt; Logout &lt;/a&gt; &lt;form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;"&gt; {{ csrf_field() }} &lt;/form&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Cheers</p>
Search values on multidimensional array then display the result <p>I'm trying to retrieve the values on multidimensional arrays using a search like function.</p> <pre><code>$rows = array( array( 'Name'=&gt;'City of God', 'Year'=&gt;'2002', 'Rating'=&gt;'10' ), array( 'Name'=&gt;'The Great Escape', 'Year'=&gt;'1963', 'Rating'=&gt;'9' ), array( 'Name'=&gt;'Dune', 'Year'=&gt;'1984', 'Rating'=&gt;'6' ), array( 'Name'=&gt;'Superbabies: Baby Geniuses 2', 'Year'=&gt;'2004', 'Rating'=&gt;'1' ) ); </code></pre> <p>So for example, if you want to search the array with a value of Name with 'City of God' and Year with '1963' the expected output should be like this </p> <pre><code>$rows = array( array( 'Name'=&gt;'City of God', 'Year'=&gt;'2002', 'Rating'=&gt;'10' ), array( 'Name'=&gt;'The Great Escape', 'Year'=&gt;'1963', 'Rating'=&gt;'9' ), ); </code></pre> <p>Currently, the function I am using is this </p> <pre><code>function multiSearch(array $array, array $pairs) { $found = array(); foreach ($array as $aKey =&gt; $aVal) { $coincidences = 0; foreach ($pairs as $pKey =&gt; $pVal) { if (array_key_exists($pKey, $aVal) &amp;&amp; $aVal[$pKey] == $pVal) { $coincidences++; } } if ($coincidences == count($pairs)) { $found[$aKey] = $aVal; } } return $found; } </code></pre> <p>However, using this function only capable of retrieving data of the same array key. So for example if I search the value of Name of 'City of God' </p> <pre><code>$x = multiSearch($rows, array('Name' =&gt; 'City of God') </code></pre> <p>This will display the correct output like this </p> <pre><code>$rows = array( array( 'Name'=&gt;'City of God', 'Year'=&gt;'2002', 'Rating'=&gt;'10' ), ); </code></pre> <p>Unfortunately, if you try to use, 'Name' => 'City of God' and 'Year' => '1963' It will not display any output. I'm stuck on figuring out on displaying the correct output, any ideas would be appreciated</p>
<p>try this it is reffered from <a href="http://stackoverflow.com/questions/8881676/how-can-i-check-if-an-array-contains-a-specific-value-in-php">How can I check if an array contains a specific value in php?</a></p> <pre><code>$array = array('kitchen', 'bedroom', 'living_room', 'dining_room'); if (in_array('kitchen', $array)) { echo 'this array contains kitchen'; } </code></pre>
How to override System.Web.HttpContext.Current.Session (MVC4) <p>I'm trying to override <code>System.Web.HttpContext.Current.Session["foo"]</code>.</p> <p>My problem is that the system is already using <code>System.Web.HttpContext.Current.Session</code> and I want to add a guid on every session name. (too many to replace)</p> <p>e.g, <code>System.Web.HttpContext.Current.Session[guid + "foo"]</code></p> <p>Is it possible for me to override the <code>get</code> and <code>set</code> property?</p>
<p>If you do not want to use an extension method and change all the already implemented code that calls the string indexer then you could roll your own provider and do it there. See <a href="https://msdn.microsoft.com/en-us/library/ms178587.aspx" rel="nofollow">Implementing a Session-State Store Provider</a>. You can then implement your "guid prefix" there.</p> <p>Here is an example of an extension method. I have no idea where you are getting <code>guid</code> from, you never mentioned this but you can take this example and add it yourself.</p> <pre><code>public static class HttpSessionStateExtension { public static object Get(this System.Web.SessionState.HttpSessionState session, string key) { var guid = ???; // no idea where or how you are getting guid, you never explained that in your question return session[guid + key]; } } // in other methods you can then call it the same as you would the indexer var result = System.Web.HttpContext.Current.Session.Get("foo"); </code></pre>
c# EF query explosion <p>Dealing with three tables - Company, Employee and User. </p> <p>Company has 0 or Many Employees. Employee has a nullable int FK to Company. In practice this alway has a value. Employee has a non nullable int FK to User. User has a bit field AccountIsDisabled. </p> <p>In my Data Model I have a partial class extending the EF model class for Company. On this the call to ActiveEmployees returning all Employees that are active for the company. </p> <p>My problem is that this code is generating a query explosion. For a company of 1K employees I am getting 1K calls to the DB. It seems EF is creating a call for each employee when navigating to the User table. </p> <p>I have tried many methods to force eager loading but to no avail. </p> <p>Anyone out there see a reason that I am getting this query explosion? </p> <pre><code>namespace JCS.Data { public partial class Company : IIdentifiable { public IEnumerable&lt;Employee&gt; ActiveEmployees { get { return Employees.Where(e =&gt; !e.User.AccountIsDisabled); } } } } </code></pre> <p>Sorry for the missing info. </p> <p>The explosion of queries occurs when a bool property on the related Employee class is accessed. Like so</p> <pre><code>namespace JCS.Data { public partial class Employee : IIdentifiable { public bool ApprovesTimesheets { get { return Company.ActiveEmployees.Any( employee =&gt; employee.TimesheetApproverEmployeeID == ID &amp;&amp; employee.TimesheetsEnabled); } } } } </code></pre> <p>So anywhere in the code I go </p> <pre><code>bool approvesTimesheets = employee.ApprovesTimesheets; </code></pre> <p>I get the 1K queries. </p> <p>I have tried adding ToLis() to the Company.ActiveEmployees. No joy. </p> <p>e.g. in Employee class</p> <pre><code>var activeEmployees = Company.ActiveEmployees.ToList(); var approvesTimesheets = activeEmployees .Any( employee =&gt; employee.TimesheetApproverEmployeeID == ID &amp;&amp; employee.TimesheetsEnabled); </code></pre> <p>the latest in a long line of failed attempts:</p> <pre><code>public List&lt;Employee&gt; ActiveEmployees { get { var employees = Employees.AsQueryable().Include(x =&gt; x.User).ToList(); return employees.Where(e =&gt; !e.User.AccountIsDisabled).ToList(); //return Employees.Where(e =&gt; !e.User.AccountIsDisabled); } } </code></pre>
<p>You need to call <code>.ToList()</code> or <code>ToListAsync()</code> to get all the data at once otherwise it will get the data on the fly per record.</p> <p>This is the problem with deferred execution VS immediate execution. When you don't materialize the list with <code>.Where(foo).ToList()</code> it loads each record whenever you try to access it therefore the 1000 DB calls.</p> <p>edit: Please note that you are also using a navigational property that points to another object (my guess is that it's object mapped directly to a table ) so, when trying to get that object you also do additional DB calls. to avoid that do something like this :</p> <pre><code>public partial class Company : IIdentifiable { public IEnumerable&lt;Employee&gt; ActiveEmployees { get { return Employees.Where(e =&gt; !e.User.AccountIsDisabled).Include(x=&gt;x.User).ToList(); } } } </code></pre>
Bash: using function with pipe as argument for another function <p>I'm trying to make function-wrapper for another functions to distinguish its in terminal</p> <pre><code>red_line="$(tput setaf 1)## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## $(tput sgr 0)" function wrapper { echo $red_line; echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)$1 $(tput sgr 0)"; $2; echo $red_line; } function foo { wrapper "custom command description" "ps axo pid,stat,pcpu,comm | tail -n 10;" } </code></pre> <p>but error was occurred: <code>ps: illegal argument: |</code></p> <p>I've tried to use <code>$(ps ... | tail -n 10)</code> and backticks instead of string and then print out result in wrapper with <code>echo $2</code>, but caught another errors</p> <p>Also tried <code>"eval $(ps ... | tail -n 10)"</code> and it also didn't work.</p> <p>Everything works just fine w/o wrapper:</p> <pre><code>function pss { echo $red_line echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)formatted 'ps ax' command $(tput sgr 0)" ps axo pid,stat,pcpu,comm | tail -n $1; echo $red_line } </code></pre> <p><a href="http://i.imgur.com/eLUqQPk.jpg" rel="nofollow">result screenshot</a></p>
<p>Tnx @chepner for referring post about passing complex commands as argument. But the actual problem was with mess with double quotes in functions arguments in <code>echo</code> and <code>wrapper</code>.</p> <p>Correct code:</p> <pre><code>red_line="$(tput setaf 1)## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## $(tput sgr 0)" function wrapper { echo $red_line; echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)$1 $(tput sgr 0)"; echo "$2"; echo $red_line; } function pss { res="$(ps axo pid,stat,pcpu,comm | tail -n $1)" wrapper "custom command description" "$res" # also work: # wrapper "custom command description" "$(ps axo pid,stat,pcpu,comm | tail -n $1)" } </code></pre>
C++ Tweetnacl hash a file without read whole file to memory <p>I'm using tweetnacl to generate sha512 hashes of strings and file. For strings it works quite well but i have no idea how to do it with files.</p> <p>The signature of the function ist</p> <pre><code>extern "C" int crypto_hash(u8 *out, const u8 *m, u64 n); </code></pre> <p>where u8 is of type unsigned char and u64 is of unsigend long long. For string a can use it like that</p> <pre><code>string s("Hello"); unsigned char h[64]; crypto_hash(h, (unsigned char *)s.c_str(), s.size()); </code></pre> <p>This works great for a string and small files but if i want to create a hash for a big file, it is not viable and uses to much memory. I searching for a solution to read the file byte by byte and pass it as unsigend char pointer to that function. Has anyone a idea how to achieve that?</p> <p>P.S Sorry for the poor English. p.s.s I use tweetnacl because of the small size and i need only the hashing function.</p>
<p>Probably the easiest way is to use a <a href="https://en.wikipedia.org/wiki/Memory-mapped_file" rel="nofollow">memory-mapped file</a>. This lets you open a file and map it into virtual memory, then you can treat the file on disk as if it is in memory, and the OS will load pages as required.</p> <p>So in your case, open your file and use <code>mmap()</code> to map it into memory. Then you can pass the pointer into your <code>crypto_hash()</code> function and let the OS do the work.</p> <p>Note that there are caveats to do with how large the file is wrt virtual memory.</p> <p>For various platforms:</p> <ul> <li><a href="http://www.boost.org/doc/libs/1_62_0/libs/iostreams/doc/classes/mapped_file.html" rel="nofollow">Boost Interprocess</a></li> <li><a href="https://developer.apple.com/library/prerelease/content/documentation/FileManagement/Conceptual/FileSystemAdvancedPT/MappingFilesIntoMemory/MappingFilesIntoMemory.html#//apple_ref/doc/uid/TP40010765-CH2-SW1" rel="nofollow">macOS and <code>mmap</code></a></li> <li><a href="https://www.safaribooksonline.com/library/view/linux-system-programming/0596009585/ch04s03.html" rel="nofollow">Linux and <code>mmap</code></a></li> <li><a href="https://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx" rel="nofollow">Windows .NET MemoryMappedFile</a></li> </ul>
need only link as an output <p>I have multiple html tag I want to extract only content of 1st href="..." for example this single line of data.</p> <pre><code>&lt;a class="product-link" data-styleid="1424359" href="/tops/biba/biba-beige--pink-women-floral-print-top/1424359/buy?src=search"&gt;&lt;img _src="http://assets.myntassets.com/h_240,q_95,w_180/v1/assets/images/1424359/2016/9/28/11475053941748-BIBA-Beige--Pink-Floral-Print-Kurti-7191475053941511-1_mini.jpg" _src2="http://assets.myntassets.com/h_307,q_95,w_230/v1/assets/images/1424359/2016/9/28/11475053941748-BIBA-Beige--Pink-Floral-Print-Kurti-7191475053941511-1_mini.jpg" alt="BIBA Beige &amp;amp; Pink Women Floral Print Top" class="lazy loading thumb" onerror="this.className='thumb error'" onload="this.className='thumb'"/&gt;&lt;div class="brand"&gt;Biba&lt;/div&gt;&lt;div class="product"&gt;Beige &amp;amp; Pink Women Floral Print Top&lt;/div&gt;&lt;div class="price"&gt;Rs. 899&lt;/div&gt;&lt;div class="sizes"&gt;Sizes: S, L, XL, XXL&lt;/div&gt;&lt;/a&gt; </code></pre> <p>I want only <code>/tops/biba/biba-beige--pink-women-floral-print-top/1424359/buy?src=search</code> as output</p> <p>The code is as follows:</p> <pre><code>from bs4 import BeautifulSoup import urllib x=urllib.urlopen("http://www.myntra.com/tops-tees-menu/") soup2 = BeautifulSoup(x, 'html.parser') for i in soup2.find_all('a', attrs={'class': 'product-link'}): print i print i.find('a')['href'] </code></pre>
<p>If you need a single "product link", just use <code>find()</code>:</p> <pre><code>soup2.find('a', attrs={'class': 'product-link'})["href"] </code></pre> <p>Note that you can use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a> location technique as well:</p> <pre><code>soup2.select_one('a.product-link')["href"] </code></pre>
ALM add-in error while trying to map excel (2013) fields with ALM fields <p>I am trying to upload test cases excel sheet to HP ALM. Below are the steps i followed to upload the sheet - Login and Auhtentication done successfully . When I click on Mapping and --> Tests it throwing me below error.</p> <p>I have double checked the (ALM) URL and is correct.</p> <p>Please Correct me if i am wrong anywhere</p> <p><strong>MS office version - 2013</strong> </p> <p><strong>ALM Add in - 12.53.94</strong> </p> <p>Downloaded from - <a href="https://hpln.hpe.com/contentoffering/microsoft-excel-add" rel="nofollow">https://hpln.hpe.com/contentoffering/microsoft-excel-add</a></p> <p><a href="https://i.stack.imgur.com/cJKIQ.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/cJKIQ.jpg" alt="enter image description here"></a></p>
<p>Check the ALM OTA Client version you're running by logging in with your browser and then click Help>About HP Application Lifecycle Management Software.</p> <p>You most likely have an older version of the OTA Client in your HPQC installation and from my experience version 12.53 of the MS Word ALM Add-in isn't compatible with some older versions of the OTA Client on the server.</p> <p>To fix this I had to remove version 12.53 of the MS Word ALM Add-in via Uninstall from Installed Programs and the download and re-install a version compatible with my own.</p> <p>You can find the list of versions if you scroll down on the download page for the MS Word ALM Add-in <a href="https://hpln.hpe.com/contentoffering/hp-alm-microsoft-word-add" rel="nofollow">https://hpln.hpe.com/contentoffering/hp-alm-microsoft-word-add</a></p>
Running the ceylon typechecker from ceylon, like in typechecker/src/main/Main.java <p>I'm running the ceylon typechecker from a ceylon project with a run.ceylon which is exactly a ceylon version of typechecker/src/main/Main.java. </p> <p>This project is supposed to typecheck itself.</p> <p>It compiles without errors, but at runtime cannot load dependencies for typechecking. </p> <p>file: source/com/example/withmodule/module.ceylon</p> <pre><code>native("jvm") module com.example.withmodule "1.0" { import com.redhat.ceylon.typechecker "1.3.0" ; //import com.redhat.ceylon.module-resolver "1.3.0"; } </code></pre> <p>file: source/com/example/withmodule/run.ceylon</p> <pre><code>import java.io{File} import com.redhat.ceylon.cmr.api{RepositoryManager} import com.redhat.ceylon.cmr.ceylon{CeylonUtils} import com.redhat.ceylon.compiler.typechecker{TypeCheckerBuilder} import com.redhat.ceylon.compiler.typechecker.io.cmr.impl{LeakingLogger} shared void run(){ value args = ["/absolutepath/ceylon-1.3.0/source/"]; RepositoryManager repositoryManager = CeylonUtils.repoManager() .systemRepo("/absolutepath/ceylon-1.3.0/repo") .logger( LeakingLogger()) .buildManager(); TypeCheckerBuilder tcb = TypeCheckerBuilder() .setRepositoryManager(repositoryManager) .verbose(true) .statistics(true); for (String path in args) { tcb.addSrcDirectory( File(path)); } tcb.typeChecker.process(); } </code></pre> <p>It compiles without errors.</p> <p>But when running it produces errors:</p> <pre><code>error [package not found in imported modules: 'com.redhat.ceylon.cmr.api' (add module import to module descriptor of 'com.example.withmodule')] at 2:7-2:31 of com/example/withmodule/withmodule.ceylon error [package not found in imported modules: 'com.redhat.ceylon.cmr.ceylon' (add module import to module descriptor of 'com.example.withmodule')] at 3:7-3:34 of com/example/withmodule/withmodule.ceylon error [package not found in imported modules: 'com.redhat.ceylon.compiler.typechecker' (add module import to module descriptor of 'com.example.withmodule')] at 4:7-4:44 of com/example/withmodule/withmodule.ceylon error [package not found in imported modules: 'com.redhat.ceylon.compiler.typechecker.io.cmr.impl' (add module import to module descriptor of 'com.example.withmodule')] at 5:7-5:56 of com/example/withmodule/withmodule.ceylon </code></pre> <p>This makes no sense to me, because compilation and typechecking had succeded just before.</p> <p>It's a fresh ceylon 1.3.0 download, not installed, simply run from the unzipped .tar.gz.</p> <p>What extra information does the typechecker need that it hadn't got?</p>
<p>So the issue here is that the typechecker we use in the test runner <code>typechecker/src/main/Main.java</code> is only able to understand things defined in Ceylon source code. It is <em>not</em> able to read a compiled Java <code>.jar</code> archive and typecheck your Ceylon source code against the classes in that archive.</p> <p>So to be able to typecheck Ceylon code that depends on Java binaries, you would need more infrastructure, including what we call a "model loader" which is responsible for building a Ceylonic model of the Java binary <code>.class</code>es. There are a number different model loaders in the Ceylon ecosystem&mdash;one for <code>javac</code>, one for Eclipse, one for IntelliJ, one that uses Java reflection, one for Dart, one for typescript, one for JS&mdash;and they're all very specific to a particular compilation environment.</p> <p>So the tests for the Ceylon typechecker, which don't depend on <code>javac</code>, IntelliJ, Eclipse, etc, etc, don't feature any sort of Java interop. Your code can successfully typecheck things defined in Ceylon source code, including code that depends on Ceylon modules with <code>.src</code> archives produced by the Ceylon compiler, but it can't typecheck things defined in a Java <code>.jar</code> archive.</p> <p>I hope that helps.</p>
change function from onclick to onload <p>I have this progress bar which loads once clicked. How do i change it from onclick to load when the page loads ?</p> <pre><code>&lt;div id="myProgress"&gt; &lt;div id="myBar"&gt; &lt;div id="label"&gt;10%&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script&gt; function move() { var elem = document.getElementById("myBar"); var width = 10; var id = setInterval(frame, 1200); function frame() { if (width &gt;= 100) { clearInterval(id); } else { width++; elem.style.width = width + '%'; document.getElementById("label").innerHTML = width * 1 + '%'; } } } &lt;/script&gt; </code></pre>
<p>You can put it on the body, onload event..</p> <p>or</p> <p>If you want to keep things all javascript, you can also use <code>document.addEventListener('DOMContentLoaded', funciton())</code></p> <p>example using body.onload</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function move() { var elem = document.getElementById("myBar"); var width = 10; var id = setInterval(frame, 1200); function frame() { if (width &gt;= 100) { clearInterval(id); } else { width++; elem.style.width = width + '%'; document.getElementById("label").innerHTML = width * 1 + '%'; } } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body onload="move()"&gt; &lt;div id="myProgress"&gt; &lt;div id="myBar"&gt; &lt;div id="label"&gt;10%&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
How to know onSurfaceTextureAvailable is called for which TextureView <p>I am writing an application where I need to display two <code>TextureView</code>(s) on my activity. I am attaching videos to each of the <code>TextureView</code> instance using <code>MediaPlayer</code> objects using the following code inside <code>onSurfaceTextureAvailable()</code>:</p> <pre><code>@Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) { Surface surface = new Surface(surfaceTexture); mMediaPlayer1 = new MediaPlayer(); try { mMediaPlayer1.setDataSource(&lt;filePath&gt;); } catch (IOException e) { Log.e(TAG, "Unable to load the file from the file system", e); return; } mMediaPlayer1.setSurface(surface); mMediaPlayer1.setLooping(true); mMediaPlayer1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { isPlaybackReady = true; } }); mMediaPlayer1.prepareAsync(); } </code></pre> <p>Now, if I have two instances of <code>TextureView</code>, how would I know the callback into <code>onSurfaceTextureAvailable(...)</code> is for which <code>TextureView</code>. </p> <p>The other way is to setup the <code>MediaPlayer</code> objects outside the <code>onSurfaceTextureAvailable(...)</code>, by getting a hold over the associated <code>SurfaceTexture</code> by calling <code>TextureView.getSurfaceTexture()</code>. I tried that as well but it always returns <code>null</code>. Is there something else that I need to do for this?</p>
<p>You can just set two instances of TextureView with different listener.</p> <pre><code>textureView1.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) { doSomething(textureView1, surfaceTexture, i, i1); } // implement other methods }); textureView2.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) { doSomething(textureView2, surfaceTexture, i, i1); } // implement other methods }); </code></pre> <p>}</p>
Changing month to different language in laravel with timesamps <p>I am trying to change/format <code>created_at</code> and <code>updated_at</code> fields created by laravel when timestamps are set to true in its model.</p> <p>suppose if the value is '2016-10-08' i want it to change as '2016-أكتوبر-08'</p> <p>Is there a way to customise the way they are stored in the database.</p> <p>I 've tried setting the locale in app.php,</p> <pre><code>'locale' =&gt; 'ar', </code></pre>
<p>Try adding this Eloquent Mutator to your model to override the base model using your set locale value (<em><code>ar</code> as defined in your <code>app.php</code></em>):</p> <pre><code>protected function asDateTime($value) { return (parent::asDateTime($value))-&gt;setLocale(App::getLocale()); } </code></pre>
Rails first or initialize not working <p>I have a product.<br> I have an order.<br> I have a booking in between.</p> <p>Whenever I make a booking from the product to the order it saves a new <strong>unique</strong> booking. </p> <p>It should:</p> <ol> <li>Save a new booking when it's the first made from this product. </li> <li>Not make a new booking, but find and overwrite an old one, if the product has already been booked once.</li> <li>If the product has already been booked on the order, but no changes are made, no database transactions are made. </li> </ol> <pre class="lang-ruby prettyprint-override"><code> def create @order = current_order @booking = @order.bookings.where(product_id: params[:product_id]).first_or_initialize product = @booking.product if @booking.new_record? @booking.product_name = product.name @booking.product_price = product.price else @booking.product_quantity = params[:product_quantity] @booking.save @order.sum_all_bookings @order.save end </code></pre> <p>Doesn't work. </p> <p><strong>Following worked:</strong></p> <pre class="lang-ruby prettyprint-override"><code> def create @booking = @order.bookings.find_by(product_id: params[:booking][:product_id]) if @booking @booking.product_quantity = params[:booking][:product_quantity] @booking.save else @booking = @order.bookings.new(booking_params) @product = @booking.product @booking.product_name = @product.name @booking.product_price = @product.price end @order.save end </code></pre> <p>Apparently I needed to grab the params, by adding <code>[:booking]</code> like in <code>params[:booking][:product_id]</code>. Anybody knows why?</p>
<p>You can try</p> <pre><code> @order.bookings.find_or_initialize_by(product_id: params[:product_id]).tap do |b| # your business logic here end </code></pre>
C++ uses twice the memory when moving elements from one dequeue to another <p>In my project, I use <a href="https://github.com/pybind/pybind11" rel="nofollow">pybind11</a> to bind C++ code to Python. Recently I have had to deal with very large data sets (70GB+) and encountered need to split data from one <code>std::deque</code> between multiple <code>std::deque</code>'s. Since my dataset is so large, I expect the split not to have much of memory overhead. Therefore I went for one pop - one push strategy, which in general should ensure that my requirements are met. </p> <p>That is all in theory. In practice, my process got killed. So I struggled for past two days and eventually came up with following minimal example demonstrating the problem.</p> <p>Generally the minimal example creates bunch of data in <code>deque</code> (~11GB), returns it to Python, then calls again to <code>C++</code> to move the elements. Simple as that. Moving part is done in executor.</p> <p>The interesting thing is, that if I don't use executor, memory usage is as expected and also when limits on virtual memory by ulimit are imposed, the program really respects these limits and doesn't crash.</p> <p><strong>test.py</strong></p> <pre><code>from test import _test import asyncio import concurrent async def test_main(loop, executor): numbers = _test.generate() # moved_numbers = _test.move(numbers) # This works! moved_numbers = await loop.run_in_executor(executor, _test.move, numbers) # This doesn't! if __name__ == '__main__': loop = asyncio.get_event_loop() executor = concurrent.futures.ThreadPoolExecutor(1) task = loop.create_task(test_main(loop, executor)) loop.run_until_complete(task) executor.shutdown() loop.close() </code></pre> <p><strong>test.cpp</strong></p> <pre><code>#include &lt;deque&gt; #include &lt;iostream&gt; #include &lt;pybind11/pybind11.h&gt; #include &lt;pybind11/stl.h&gt; namespace py = pybind11; PYBIND11_MAKE_OPAQUE(std::deque&lt;uint64_t&gt;); PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr&lt;T&gt;); template&lt;class T&gt; void py_bind_opaque_deque(py::module&amp; m, const char* type_name) { py::class_&lt;std::deque&lt;T&gt;, std::shared_ptr&lt;std::deque&lt;T&gt;&gt;&gt;(m, type_name) .def(py::init&lt;&gt;()) .def(py::init&lt;size_t, T&gt;()); } PYBIND11_PLUGIN(_test) { namespace py = pybind11; pybind11::module m("_test"); py_bind_opaque_deque&lt;uint64_t&gt;(m, "NumbersDequeue"); // Generate ~11Gb of data. m.def("generate", []() { std::deque&lt;uint64_t&gt; numbers; for (uint64_t i = 0; i &lt; 1500 * 1000000; ++i) { numbers.push_back(i); } return numbers; }); // Move data from one dequeue to another. m.def("move", [](std::deque&lt;uint64_t&gt;&amp; numbers) { std::deque&lt;uint64_t&gt; numbers_moved; while (!numbers.empty()) { numbers_moved.push_back(std::move(numbers.back())); numbers.pop_back(); } std::cout &lt;&lt; "Done!\n"; return numbers_moved; }); return m.ptr(); } </code></pre> <p><strong>test/__init__.py</strong></p> <pre><code>import warnings warnings.simplefilter("default") </code></pre> <p><strong>Compilation</strong>:</p> <pre><code>g++ -std=c++14 -O2 -march=native -fPIC -Iextern/pybind11 `python3.5-config --includes` `python3.5-config --ldflags` `python3.5-config --libs` -shared -o test/_test.so test.cpp </code></pre> <p><strong>Observations:</strong></p> <ul> <li>When the moving part is not done by executor, so we just call <code>moved_numbers = _test.move(numbers)</code>, all works as expected, memory usage showed by htop stays around <code>11Gb</code>, great!.</li> <li>When moving part is done in executor, the program takes double the memory and crashes.</li> <li><p>When limits on virtual memory are introduced (~15Gb), all works fine, which is probably the most interesting part.</p> <p><code>ulimit -Sv 15000000 &amp;&amp; python3.5 test.py</code> >> <code>Done!</code>.</p></li> <li><p>When we increase the limit the program crashes (150Gb > my RAM).</p> <p><code>ulimit -Sv 150000000 &amp;&amp; python3.5 test.py</code> >> <code>[1] 2573 killed python3.5 test.py</code></p></li> <li><p>Usage of deque method <code>shrink_to_fit</code> doesn't help (And nor it should)</p></li> </ul> <p><strong>Used software</strong></p> <pre><code>Ubuntu 14.04 gcc version 5.4.1 20160904 (Ubuntu 5.4.1-2ubuntu1~14.04) Python 3.5.2 pybind11 latest release - v1.8.1 </code></pre> <p><strong>Note</strong></p> <p>Please note that this example was made merely to demonstrate the problem. Usage of <code>asyncio</code> and <code>pybind</code> is necessary for problem to occur. </p> <p>Any ideas on what might be going on are most welcomed.</p>
<p>The problem turned out to be caused by Data being created in one thread and then deallocated in another one. It is so because of malloc arenas in glibc <a href="https://siddhesh.in/posts/malloc-per-thread-arenas-in-glibc.html" rel="nofollow">(for reference see this)</a>. It can be nicely demonstrated by doing:</p> <pre><code>executor1 = concurrent.futures.ThreadPoolExecutor(1) executor2 = concurrent.futures.ThreadPoolExecutor(1) numbers = await loop.run_in_executor(executor1, _test.generate) moved_numbers = await loop.run_in_executor(executor2, _test.move, numbers) </code></pre> <p>which would take twice the memory allocated by <code>_test.generate</code> and</p> <pre><code>executor = concurrent.futures.ThreadPoolExecutor(1) numbers = await loop.run_in_executor(executor, _test.generate) moved_numbers = await loop.run_in_executor(executor, _test.move, numbers) </code></pre> <p>which wound't.</p> <p>This issue can be solved either by rewriting the code so it doesn't move the elements from one container to another (my case) or by setting environment variable <code>export MALLOC_ARENA_MAX=1</code> which will limit number of malloc arenas to 1. This however might have some performance implications involved (There is a good reason for having multiple arenas).</p>
Vimrc not updating <p>I am trying to setup vim to wrap my git commits to 72 characters but I am having trouble doing so. When I edit ":e $myvimrc" and add the settings to wrap the text it doesn't seem to work. I tried to open the vimrc file directly form my program files to check that the changes I have made had indeed been saved, but they are not showing in the file.</p> <p>Strange thing is that when I open the vimrc file in vim to edit it the changes I made are still there, they just don't seem to be saving to the actual file.</p> <p>I have tried to edit the vimrc directly as well but it wont allow me to save in that location. Hopefully im just doing something silly and if I am I apologies, very fresh to git and vim. Thanks in advance </p>
<p>usually you don't need do special setting for gitcommit Filetype. Because GITCOMMIT was pre-defined as <code>wrap &amp; textwidth=72</code> under your <code>$VIMRUNTIME/ftplugin/gitcommit.vim</code></p> <p>Check if you have <code>filetype on</code> in your vimrc, so that the filetype plugins are activated. </p>
Is it possible to extend Test Cases in Nightwatch? <p>Does anyone has experience with extending Test Cases in Nightwatch. I want to have some main Test Case and than the same Test Case to extend it with few more functions. For example I have one Test Case which works fine on Desktop, but in order to work on Mobile device I need to click one more button, so I want to crate new Test Case which will extend the Test Case for Desktop and than will click on the required button?I don't want to use custom commands</p>
<p>I use page objects for this, where all "clicky" logic is abstracted into little functions about "user intent". That could be ideal for what you're talking about. I also use globals to inject my browser name into my test_settings in nightwatch.json so I can test on it, or include it in screenshot names. You could use this to decide whether to do your extra click.</p> <pre><code>... "ie10": { "selenium_host": "10.20.3.161", "desiredCapabilities": { "browserName": "internet explorer", "javascriptEnabled": true, "acceptSslCerts": true, "ie.ensureCleanSession": true }, "globals": { "env": "ie10" } }, ... </code></pre>
Extracting href from Nodelist <pre><code>var downloadLinks = document.querySelectorAll('[href*="/Download"]'); </code></pre> <p>gives me the NodeList with all elements, but how do I extract just the <code>href</code> value from all the nodes as a single array?</p> <p>I tried <code>return Array.from(downloadLinks)</code> but looks like PhantomJS doesn't support ES6 so I get <code>TypeError: undefined is not a function</code></p>
<pre><code>var downloadLinks = document.querySelectorAll('[href*="/Download"]'); var arrHREF = []; // create an Array to save hrefs var i = 0; for(; i&lt;downloadLinks.length; i++) { arrHREF.push(downloadLinks[i].href); // push hrefs in array } </code></pre> <p>or you can write it in one line as (using the for loop property of declaring variables in execution brackets)</p> <pre><code>for (var downloadLinks = document.querySelectorAll('[href*="/Download"]'), arrHREF = [], i = 0; i &lt; downloadLinks.length; i++) arrHREF.push(downloadLinks[i].href); </code></pre>
Fullcalendar wordpress submit booking <p>i need creat this <a href="https://i.stack.imgur.com/ACGYi.png" rel="nofollow">calendar</a> i use fullcalendar jquery but i have many problem for integrate on my php page. I need save data for update woo commerce booking or save with submit listing job (wp jobmanager). Thank you for your help</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>jQuery(document).ready(function($) { /* initialize the external events -----------------------------------------------------------------*/ $('#external-events div.external-event').each(function() { //console.log($(this)); // events drags var eventObject = { title: $.trim($(this).text()), className: $(this).attr('className'), color: $(this).attr('color'), type: $(this).attr('type'), textColor: $(this).attr('textColor'), }; // store the Event Object in the DOM element so we can get to it later $(this).data('eventObject', eventObject); $.fullCalendar.formatDate(eventObject.start,'yyyy-MM-dd'); // make the event draggable using jQuery UI $(this).draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); }); // inti calendar $('#calendar').fullCalendar({ header: { left: 'today', center: 'title', right: 'prev,next', }, height: 350, aspectRatio: 1, //contentHeight: 600, editable: true, droppable: true, events: $('#calendar').attr('values'), // on dropping drop: function(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); // we need to copy it, so that multiple events don't have a reference to the same object var copiedEventObject = $.extend({}, originalEventObject); // assign it the date that was reported copiedEventObject.start = $.fullCalendar.formatDate(date,'yyyy-MM-dd'); copiedEventObject.end = $.fullCalendar.formatDate(date,'yyyy-MM-dd'); copiedEventObject.allDay = allDay; // render the event on the calendar $('#calendar').fullCalendar('renderEvent', copiedEventObject, true); // Get currents dates var startCurrent = new Date(copiedEventObject.start); if (copiedEventObject.end == null) { var endCurrent = startCurrent; } else { var endCurrent = new Date(copiedEventObject.end); } // Get events dates var pulledEvents = $('#calendar').fullCalendar( 'clientEvents'); // Compare to events dates var nbEventCheck = pulledEvents.length-1; for (var i = 0; i &lt; nbEventCheck; i++) { var startPulled = new Date(pulledEvents[i].start); var endPulled = new Date(pulledEvents[i].end); if (endPulled.getTime() == 0) { endPulled = startPulled; } // containing if (startCurrent &gt;= startPulled &amp;&amp; endCurrent &lt;= endPulled) { // begin if (startCurrent.getTime() == startPulled.getTime()) { // start pulledEvent later pulledEvents[i].start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); // if same remove if (endCurrent.getTime() == endPulled.getTime()) { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id); } } // finish else if (endCurrent.getTime() == endPulled.getTime()) { // finish pulledEvent earlier pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); } // contain else { // copy pulledEvent to the end var copiedpulledEvent = $.extend({}, pulledEvents[i]); copiedpulledEvent._id = "copy"+Math.floor((Math.random()*1000)+1);; copiedpulledEvent.source = null; copiedpulledEvent.start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); copiedpulledEvent.end = pulledEvents[i].end; $('#calendar').fullCalendar('renderEvent', copiedpulledEvent, true); // cut beginning pulledEvent pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('addEventSource', pulledEvents[i]); $('#calendar').fullCalendar('renderEvent', pulledEvents[i], true); } } } }, // on dropping from calendar eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) { // Get currents dates var startCurrent = new Date(event.start); if (event.end == null) { var endCurrent = startCurrent; } else { var endCurrent = new Date(event.end); } // Get events dates var pulledEvents = $('#calendar').fullCalendar( 'clientEvents'); // Compare to events dates var nbEventCheck = pulledEvents.length; for (var i = 0; i &lt; nbEventCheck; i++) { // avoid to compare to the same copy element if (event._id == pulledEvents[i]._id) { i++; if (i &gt;= nbEventCheck) { break; } } var startPulled = new Date(pulledEvents[i].start); var endPulled = new Date(pulledEvents[i].end); if (endPulled.getTime() == 0) { endPulled = startPulled; } // containing if (startCurrent &gt;= startPulled &amp;&amp; endCurrent &lt;= endPulled) { // begin if (startCurrent.getTime() == startPulled.getTime()) { // start pulledEvent later pulledEvents[i].start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); // if same remove if (endCurrent.getTime() == endPulled.getTime()) { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id) } } // finish else if (endCurrent.getTime() == endPulled.getTime()) { // finish pulledEvent earlier pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); } // contain else { // copy pulledEvent to the end var copiedpulledEvent = $.extend({}, pulledEvents[i]); copiedpulledEvent._id = "copy"+Math.floor((Math.random()*1000)+1); copiedpulledEvent.source = null; copiedpulledEvent.start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); copiedpulledEvent.end = pulledEvents[i].end; $('#calendar').fullCalendar('renderEvent', copiedpulledEvent, true); // cut beginning pulledEvent pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('addEventSource', pulledEvents[i]); $('#calendar').fullCalendar('renderEvent', pulledEvents[i], true); } // update pulledEvent var startPulled = new Date(pulledEvents[i].start); var endPulled = new Date(pulledEvents[i].end); } // externing if (startCurrent &lt;= endPulled &amp;&amp; endCurrent &gt;= startPulled) { // left if (endCurrent &lt;= endPulled) { pulledEvents[i].start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); // if same remove if (endCurrent.getTime() == endPulled.getTime()) { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id) } } // right else if (startCurrent &gt;= startPulled) { pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); if (startCurrent.getTime() == startPulled.getTime()) { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id) } } // surround else { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id); } } } }, // on event resizing eventResize: function (event, dayDelta, minuteDelta, revertFunc) { // Get currents dates var startCurrent = new Date(event.start); if (event.end == null) { var endCurrent = startCurrent; } else { var endCurrent = new Date(event.end); } // Get events dates var pulledEvents = $('#calendar').fullCalendar( 'clientEvents'); // Compare to events dates var nbEventCheck = pulledEvents.length; for (var i = 0; i &lt; nbEventCheck; i++) { // avoid to compare to the same copy element if (event._id == pulledEvents[i]._id) { i++; if (i &gt;= nbEventCheck) { break; } } var startPulled = new Date(pulledEvents[i].start); var endPulled = new Date(pulledEvents[i].end); if (endPulled.getTime() == 0) { endPulled = startPulled; } // externing if (startCurrent &lt;= endPulled &amp;&amp; endCurrent &gt;= startPulled) { // left if (endCurrent &lt; endPulled) { pulledEvents[i].start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); } // right else if (startCurrent &gt; startPulled) { pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); } // surround else { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id); } } } }, // on click on event eventClick: function(calEvent, jsEvent, view) { if (confirm('Remove this event ?')) { $('#calendar').fullCalendar('removeEvents',calEvent._id); } } // get localized date format using Moment.js // var lang = jQuery('html').attr('lang') || 'en'; // var locale = moment().locale(lang); var dateFormat = "d-m-y"; // get origin date format from query string var originFormat = dateFormat; // if (originFormat) { // originFormat = convertPHPFormatMoment(originFormat); // } // reformat date for current locale if different of origin format if (originFormat &amp;&amp; originFormat != dateFormat) { var startField = $("#datepicker-start"), endField = $("#datepicker-end"), startDate = moment(startField.val(), originFormat), endDate = moment(endField.val(), originFormat); startField.val( startDate.format(dateFormat) ); endField.val( endDate.format(dateFormat) ); } // add hidden date_format field $("#datepicker-start").closest('form').append('&lt;input type="hidden" name="date_format" id="date_format" value="'+ dateFormat +'"&gt;'); $("#datepicker-start").datepicker({ dateFormat: dateFormat, minDate: 0, showButtonPanel: true, onClose: function (selectedDate) { $("#datepicker-end").datepicker("option", "minDate", selectedDate); $("#datepicker-end").focus(); } }); $("#datepicker-end").datepicker({ dateFormat: dateFormat, minDate: 0, showButtonPanel: true, onClose: function (selectedDate) { $("#datepicker-start").datepicker("option", "maxDate", selectedDate); } }); $('#calendar').fullCalendar('renderEvent', newEvent, true); $('#calendar').fullCalendar('gotoDate', newEvent.start); var color = $("#default-events label.active input").attr("color"); $('td.fc-day').css('background-color', color); // empty date $('#datepicker-start').val(''); $('#datepicker-end').val(''); // reset bounds dates $('#datepicker-start').datepicker("option", "maxDate", null); $('#datepicker-end').datepicker("option", "minDate", null); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="&lt;?php echo get_template_directory_uri(); ?&gt;/fullcalendar/jquery-ui-1.10.3.custom.min.css" media="screen" rel="stylesheet" type="text/css"&gt; &lt;link href="&lt;?php echo get_template_directory_uri(); ?&gt;/fullcalendar/fullcalendar.css" media="screen" rel="stylesheet" type="text/css"&gt; &lt;script type="text/javascript" src="&lt;?php echo get_template_directory_uri(); ?&gt;/fullcalendar/moment.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo get_template_directory_uri(); ?&gt;/fullcalendar/jquery-ui.custom.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo get_template_directory_uri(); ?&gt;/fullcalendar/jquery-ui-1.10.3.custom.datepicker.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo get_template_directory_uri(); ?&gt;/fullcalendar/fullcalendar-gtg.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo get_template_directory_uri(); ?&gt;/fullcalendar/fullcalendar.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo get_template_directory_uri(); ?&gt;/fullcalendar/i18n/jquery.ui.datepicker-fr.js"&gt;&lt;/script&gt; &lt;div class="tab-pane fade active in" id="calendar_home" style="display:initial;"&gt; &lt;div id="progress"&gt; &lt;div class="bar bar-photo-edit" style="display:none;"&gt; &lt;span&gt;Chargement en cours…&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="alert-box"&gt; &lt;div id="calendar-not-uptodate" class="alert alert-warning alert-calendar" style="display: initial;"&gt; Vous n'avez aucune période selectionné &lt;/div&gt; &lt;div style="display: none;" class="alert alert-success alert-calendar" id="calendar-updated"&gt; Votre calendrier a été mis à jour &lt;/div&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;!-- date picker --&gt; &lt;div id="datepicker-event" class="form-inline"&gt; &lt;label class="home_type"&gt;Créer une nouvelle période de disponibilité&lt;/label&gt; &lt;div&gt; &lt;div class="form-group calendar-edition"&gt; &lt;input id="datepicker-start" class="form-control " type="text" placeholder="Du" /&gt; &lt;/div&gt; &lt;div class="form-group calendar-edition"&gt; &lt;input id="datepicker-end" class="form-control " type="text" placeholder="jusqu'au" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;select class="form-control"&gt; &lt;option value="0" disabled="" selected=""&gt;Type de disponibilité&lt;/option&gt; &lt;option title="Disponible" classname="event-available" color="#d4f2e6" value="5"&gt;Disponible&lt;/option&gt; &lt;option title="Flexible" classname="event-ask-me" color="#CDE5f9" value="3"&gt;Flexible me contacter&lt;/option&gt; &lt;option title="Indisponible" classname="external-events event-unavailable" color="#E7E7E7" value="1"&gt;Indisponible&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;input class="btn btn-default calendar-edition" type="button" id="add_date" value="submit"&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- #datepicker-event --&gt; &lt;div id="datepicker-event"&gt;&lt;/div&gt; &lt;!-- popup period delete --&gt; &lt;div class="modal fade" id="deletePeriod" style="display: none;"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;×&lt;/span&gt; &lt;/button&gt; &lt;h4 class="modal-title" id="myModalLabel"&gt;Etes-vous sûr?&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;Etes-vous sûr de vouloir supprimer cette période ?&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-default btn-basic" data-dismiss="modal"&gt;Annuler&lt;/button&gt; &lt;button type="button" class="btn btn-primary" data-dismiss="modal" id="delete_period"&gt;Supprimer&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- calendar --&gt; &lt;div id="calendar" class="fc fc-ltr" value=""&gt; &lt;/div&gt; &lt;!-- default value --&gt; &lt;div id="default-events"&gt; &lt;label class=""&gt;Disponibilité par défaut &lt;span class="grey-color small italic text-default-value"&gt;Choisissez l'option qui décrit le mieux la disponibilité de votre maison durant l'année&lt;/span&gt;&lt;/label&gt; &lt;label class="radio default-available active"&gt; &lt;input type="radio" color="#d4f2e6" name="default-date" id="default-date-4" value="4"&gt; &lt;span class="color-available small"&gt;Disponible&lt;/span&gt; Ma maison est généralement disponible &lt;/label&gt; &lt;label class="radio default-ask-me"&gt; &lt;input type="radio" color="#CDE5f9" name="default-date" id="default-date-2" value="2" &gt; &lt;span class="color-ask-me small"&gt;Demandez moi&lt;/span&gt; Mes dates sont flexibles &lt;/label&gt; &lt;label class="radio default-unavailable"&gt; &lt;input type="radio" color="#E7E7E7" name="default-date" id="default-date-0" value="0"&gt; &lt;span class="color-unavailable small"&gt;Indisponible&lt;/span&gt; Ma maison est habituellement indisponible &lt;/label&gt; &lt;label class="default-guestwanted"&gt; &lt;span class="color-wanted small"&gt;test&lt;/span&gt; Je recherche activement des Invités &lt;br&gt; &lt;small&gt;&lt;em&gt;(période non disponible par défaut)&lt;/em&gt;&lt;/small&gt; &lt;/label&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;div id="return-message"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
<p>Next update but don't work. I need save availability of fullcalendar custom in wp job manager user as a field and update to availabity woo commerce booking calendar product. If anyone has a good idea on how to do this better, </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { /* initialize the external events -----------------------------------------------------------------*/ $('#external-events div.external-event').each(function() { //console.log($(this)); // events drags var eventObject = { title: $.trim($(this).text()), className: $(this).attr('className'), color: $(this).attr('color'), type: $(this).attr('type'), textColor: $(this).attr('textColor'), }; // store the Event Object in the DOM element so we can get to it later $(this).data('eventObject', eventObject); $.fullCalendar.formatDate(eventObject.start,'yyyy-MM-dd'); // make the event draggable using jQuery UI $(this).draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); }); // inti calendar $('#calendar').fullCalendar({ header: { left: 'today', center: 'title', right: 'prev,next', }, height: 350, aspectRatio: 1, //contentHeight: 600, editable: true, droppable: true, events: $('#calendar').attr('values'), // on dropping drop: function(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); // we need to copy it, so that multiple events don't have a reference to the same object var copiedEventObject = $.extend({}, originalEventObject); // assign it the date that was reported copiedEventObject.start = $.fullCalendar.formatDate(date,'yyyy-MM-dd'); copiedEventObject.end = $.fullCalendar.formatDate(date,'yyyy-MM-dd'); copiedEventObject.allDay = allDay; // render the event on the calendar $('#calendar').fullCalendar('renderEvent', copiedEventObject, true); // Get currents dates var startCurrent = new Date(copiedEventObject.start); if (copiedEventObject.end == null) { var endCurrent = startCurrent; } else { var endCurrent = new Date(copiedEventObject.end); } // Get events dates var pulledEvents = $('#calendar').fullCalendar( 'clientEvents'); // Compare to events dates var nbEventCheck = pulledEvents.length-1; for (var i = 0; i &lt; nbEventCheck; i++) { var startPulled = new Date(pulledEvents[i].start); var endPulled = new Date(pulledEvents[i].end); if (endPulled.getTime() == 0) { endPulled = startPulled; } // containing if (startCurrent &gt;= startPulled &amp;&amp; endCurrent &lt;= endPulled) { // begin if (startCurrent.getTime() == startPulled.getTime()) { // start pulledEvent later pulledEvents[i].start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); // if same remove if (endCurrent.getTime() == endPulled.getTime()) { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id); } } // finish else if (endCurrent.getTime() == endPulled.getTime()) { // finish pulledEvent earlier pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); } // contain else { // copy pulledEvent to the end var copiedpulledEvent = $.extend({}, pulledEvents[i]); copiedpulledEvent._id = "copy"+Math.floor((Math.random()*1000)+1);; copiedpulledEvent.source = null; copiedpulledEvent.start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); copiedpulledEvent.end = pulledEvents[i].end; $('#calendar').fullCalendar('renderEvent', copiedpulledEvent, true); // cut beginning pulledEvent pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('addEventSource', pulledEvents[i]); $('#calendar').fullCalendar('renderEvent', pulledEvents[i], true); } } } }, // on dropping from calendar eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) { // Get currents dates var startCurrent = new Date(event.start); if (event.end == null) { var endCurrent = startCurrent; } else { var endCurrent = new Date(event.end); } // Get events dates var pulledEvents = $('#calendar').fullCalendar( 'clientEvents'); // Compare to events dates var nbEventCheck = pulledEvents.length; for (var i = 0; i &lt; nbEventCheck; i++) { // avoid to compare to the same copy element if (event._id == pulledEvents[i]._id) { i++; if (i &gt;= nbEventCheck) { break; } } var startPulled = new Date(pulledEvents[i].start); var endPulled = new Date(pulledEvents[i].end); if (endPulled.getTime() == 0) { endPulled = startPulled; } // containing if (startCurrent &gt;= startPulled &amp;&amp; endCurrent &lt;= endPulled) { // begin if (startCurrent.getTime() == startPulled.getTime()) { // start pulledEvent later pulledEvents[i].start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); // if same remove if (endCurrent.getTime() == endPulled.getTime()) { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id) } } // finish else if (endCurrent.getTime() == endPulled.getTime()) { // finish pulledEvent earlier pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); } // contain else { // copy pulledEvent to the end var copiedpulledEvent = $.extend({}, pulledEvents[i]); copiedpulledEvent._id = "copy"+Math.floor((Math.random()*1000)+1); copiedpulledEvent.source = null; copiedpulledEvent.start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); copiedpulledEvent.end = pulledEvents[i].end; $('#calendar').fullCalendar('renderEvent', copiedpulledEvent, true); // cut beginning pulledEvent pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('addEventSource', pulledEvents[i]); $('#calendar').fullCalendar('renderEvent', pulledEvents[i], true); } // update pulledEvent var startPulled = new Date(pulledEvents[i].start); var endPulled = new Date(pulledEvents[i].end); } // externing if (startCurrent &lt;= endPulled &amp;&amp; endCurrent &gt;= startPulled) { // left if (endCurrent &lt;= endPulled) { pulledEvents[i].start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); // if same remove if (endCurrent.getTime() == endPulled.getTime()) { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id) } } // right else if (startCurrent &gt;= startPulled) { pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); if (startCurrent.getTime() == startPulled.getTime()) { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id) } } // surround else { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id); } } } }, // on event resizing eventResize: function (event, dayDelta, minuteDelta, revertFunc) { // Get currents dates var startCurrent = new Date(event.start); if (event.end == null) { var endCurrent = startCurrent; } else { var endCurrent = new Date(event.end); } // Get events dates var pulledEvents = $('#calendar').fullCalendar( 'clientEvents'); // Compare to events dates var nbEventCheck = pulledEvents.length; for (var i = 0; i &lt; nbEventCheck; i++) { // avoid to compare to the same copy element if (event._id == pulledEvents[i]._id) { i++; if (i &gt;= nbEventCheck) { break; } } var startPulled = new Date(pulledEvents[i].start); var endPulled = new Date(pulledEvents[i].end); if (endPulled.getTime() == 0) { endPulled = startPulled; } // externing if (startCurrent &lt;= endPulled &amp;&amp; endCurrent &gt;= startPulled) { // left if (endCurrent &lt; endPulled) { pulledEvents[i].start = new Date(endCurrent.getTime() + (1000 * 60 * 60 * 24 * 1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); } // right else if (startCurrent &gt; startPulled) { pulledEvents[i].end = new Date(startCurrent.getTime() + (1000 * 60 * 60 * 24 * -1)); $('#calendar').fullCalendar('updateEvent', pulledEvents[i]); } // surround else { $('#calendar').fullCalendar('removeEvents',pulledEvents[i]._id); } } } }, // on click on event eventClick: function(calEvent, jsEvent, view) { if (confirm('Remove this event ?')) { $('#calendar').fullCalendar('removeEvents',calEvent._id); } } }); // get localized date format using Moment.js // var lang = jQuery('html').attr('lang') || 'en'; // var locale = moment().locale(lang); var dateFormat = "d-m-y"; // get origin date format from query string var originFormat = dateFormat; // if (originFormat) { // originFormat = convertPHPFormatMoment(originFormat); // } // reformat date for current locale if different of origin format if (originFormat &amp;&amp; originFormat != dateFormat) { var startField = $("#datepicker-start"), endField = $("#datepicker-end"), startDate = moment(startField.val(), originFormat), endDate = moment(endField.val(), originFormat); startField.val( startDate.format(dateFormat) ); endField.val( endDate.format(dateFormat) ); } // add hidden date_format field $("#datepicker-start").closest('form').append('&lt;input type="hidden" name="date_format" id="date_format" value="'+ dateFormat +'"&gt;'); $("#datepicker-start").datepicker({ dateFormat: dateFormat, minDate: 0, showButtonPanel: true, onClose: function (selectedDate) { $("#datepicker-end").datepicker("option", "minDate", selectedDate); $("#datepicker-end").focus(); } }); $("#datepicker-end").datepicker({ dateFormat: dateFormat, minDate: 0, showButtonPanel: true, onClose: function (selectedDate) { $("#datepicker-start").datepicker("option", "maxDate", selectedDate); } }); $('#calendar').fullCalendar('renderEvent', newEvent, true); $('#calendar').fullCalendar('gotoDate', newEvent.start); var color = $("#default-events label.active input").attr("color"); $('td.fc-day').css('background-color', color); // empty date $('#datepicker-start').val(''); $('#datepicker-end').val(''); // reset bounds dates $('#datepicker-start').datepicker("option", "maxDate", null); $('#datepicker-end').datepicker("option", "minDate", null); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://free-communiity.com/wp-content/themes/listable-172/listable/fullcalendar/i18n/jquery.ui.datepicker-fr.js"&gt;&lt;/script&gt; &lt;link href="https://free-communiity.com/wp-content/themes/listable-172/listable/fullcalendar/jquery-ui-1.10.3.custom.min.css" media="screen" rel="stylesheet" type="text/css"&gt; &lt;link href="https://free-communiity.com/wp-content/themes/listable-172/listable/fullcalendar/fullcalendar.css" media="screen" rel="stylesheet" type="text/css"&gt; &lt;script src="https://free-communiity.com/wp-content/themes/listable-172/listable/fullcalendar/moment.js"&gt;&lt;/script&gt; &lt;script src="https://free-communiity.com/wp-content/themes/listable-172/listable/fullcalendar/jquery-ui.custom.min.js"&gt;&lt;/script&gt; &lt;script src="https://free-communiity.com/wp-content/themes/listable-172/listable/fullcalendar/jquery-ui-1.10.3.custom.datepicker.min.js"&gt;&lt;/script&gt; &lt;script src="https://free-communiity.com/wp-content/themes/listable-172/listable/fullcalendar/fullcalendar-gtg.js"&gt;&lt;/script&gt; &lt;script src="https://free-communiity.com/wp-content/themes/listable-172/listable/fullcalendar/datepicker-custom.js"&gt;&lt;/script&gt; &lt;script src="https://free-communiity.com/wp-content/themes/listable-172/listable/fullcalendar/fullcalendar.min.js"&gt;&lt;/script&gt; &lt;div class="tab-pane fade active in" id="calendar_home" style="display:initial;"&gt; &lt;div id="progress"&gt; &lt;div class="bar bar-photo-edit" style="display:none;"&gt; &lt;span&gt;Chargement en cours…&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="alert-box"&gt; &lt;div id="calendar-not-uptodate" class="alert alert-warning alert-calendar" style="display: initial;"&gt; Vous n'avez aucune période selectionné &lt;/div&gt; &lt;div style="display: none;" class="alert alert-success alert-calendar" id="calendar-updated"&gt; Votre calendrier a été mis à jour &lt;/div&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;!-- date picker --&gt; &lt;div id="datepicker-event" class="form-inline"&gt; &lt;label class="home_type"&gt;Créer une nouvelle période de disponibilité&lt;/label&gt; &lt;div&gt; &lt;div class="form-group calendar-edition"&gt; &lt;input id="datepicker-start" class="form-control " type="text" placeholder="Du" /&gt; &lt;/div&gt; &lt;div class="form-group calendar-edition"&gt; &lt;input id="datepicker-end" class="form-control " type="text" placeholder="jusqu'au" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;select class="form-control"&gt; &lt;option value="0" disabled="" selected=""&gt;Type de disponibilité&lt;/option&gt; &lt;option title="Disponible" classname="event-available" color="#d4f2e6" value="5"&gt;Disponible&lt;/option&gt; &lt;option title="Flexible" classname="event-ask-me" color="#CDE5f9" value="3"&gt;Flexible me contacter&lt;/option&gt; &lt;option title="Indisponible" classname="external-events event-unavailable" color="#E7E7E7" value="1"&gt;Indisponible&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;input class="btn btn-default calendar-edition" type="button" id="add_date" value="submit"&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- #datepicker-event --&gt; &lt;div id="datepicker-event"&gt;&lt;/div&gt; &lt;!-- popup period delete --&gt; &lt;div class="modal fade" id="deletePeriod" style="display: none;"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;×&lt;/span&gt; &lt;/button&gt; &lt;h4 class="modal-title" id="myModalLabel"&gt;Etes-vous sûr?&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;Etes-vous sûr de vouloir supprimer cette période ?&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-default btn-basic" data-dismiss="modal"&gt;Annuler&lt;/button&gt; &lt;button type="button" class="btn btn-primary" data-dismiss="modal" id="delete_period"&gt;Supprimer&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- calendar --&gt; &lt;div id="calendar" class="" value=""&gt; &lt;/div&gt; &lt;!-- default value --&gt; &lt;div id="default-events"&gt; &lt;label class=""&gt;Disponibilité par défaut &lt;span class="grey-color small italic text-default-value"&gt;Choisissez l'option qui décrit le mieux la disponibilité de votre maison durant l'année&lt;/span&gt;&lt;/label&gt; &lt;label class="radio default-available active"&gt; &lt;input type="radio" color="#d4f2e6" name="default-date" id="default-date-4" value="4"&gt; &lt;span class="color-available small"&gt;Disponible&lt;/span&gt; Ma maison est généralement disponible &lt;/label&gt; &lt;label class="radio default-ask-me"&gt; &lt;input type="radio" color="#CDE5f9" name="default-date" id="default-date-2" value="2" &gt; &lt;span class="color-ask-me small"&gt;Demandez moi&lt;/span&gt; Mes dates sont flexibles &lt;/label&gt; &lt;label class="radio default-unavailable"&gt; &lt;input type="radio" color="#E7E7E7" name="default-date" id="default-date-0" value="0"&gt; &lt;span class="color-unavailable small"&gt;Indisponible&lt;/span&gt; Ma maison est habituellement indisponible &lt;/label&gt; &lt;label class="default-guestwanted"&gt; &lt;span class="color-wanted small"&gt;test&lt;/span&gt; Je recherche activement des Invités &lt;br&gt; &lt;small&gt;&lt;em&gt;(période non disponible par défaut)&lt;/em&gt;&lt;/small&gt; &lt;/label&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;div id="return-message"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
Creating a recursive function for calculating R = x - N * y, with conditions <p>I wish to create a function for calculating R = x - N * y, where x and y are floats and N is the largest positive integer, so that x > N * y.</p> <p>The function should only take the inputs of x and y.</p> <p>I have previously created the function through a loop, but having trouble trying to convert it to recursion. My basic idea is something like:</p> <pre><code>def florec(x, y): if x &gt; y: R = x - N * y florec(x, y_increased) return R </code></pre> <p>My problem is that I can not figure out how to code "y_increased", meaning, how I can update N to N+1, and then call upon florec(x, (N+1)*y). Then update N+1 to N+2 and call upon florec(x, (N+2)*y) and so on.</p> <p>Feeling quite stuck currently, so any help at all to move forward would be appreciated.</p>
<p>Here's a recursive way of computing R:</p> <pre><code>def florec(x, y): if x &gt; y: return florec(x-y, y) return x </code></pre> <p>(Note it only works for positive floats.)</p> <p>I don't know if this addresses your recursion issues. Maybe this use case is not best suited to illustrate recursion.</p>
Get parent url parameter <p>I have this routing</p> <pre><code>import { ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; import { AppComponent } from './app.component'; import { ChildComponent } from './app.child-component'; import { Child2Component } from './child2-component'; const appRoutes: Routes = [ { path: '', redirectTo: 'AppComponent', pathMatch: 'full' }, { path: ':lang', children: [ { path: '', component: ChildComponent }, { path: 'Child2Component', component: Child2Component } ] } ]; export const appRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes); </code></pre> <p>I want to get that lang parameter from my function which looks:</p> <pre><code>translateThis(lang: any) { // this line works fine this.translate.use(lang); // this doesn't this.sub = this.route.parent.queryParams.subscribe( (param: any) =&gt; { let lang = param['lang']; console.log(param); console.log(userId); }); } </code></pre> <p>but it stops working as soon i uncomment this.sub code (whole 6 lines). without that it works ok</p> <pre><code>translateThis(lang: any) { this.translate.use(lang); } </code></pre> <p>How can I get that lang value? I tried <code>params</code> as well instead of queryParams but result is same</p>
<p>I guess this is what you are looking for</p> <pre><code>translateThis() { // Subscribe to router params observable this.sub= this.route.parent.params.subscribe( param =&gt; { let lang = param['lang']; console.log(lang); // Call method or something this.translate.use(lang); }); } </code></pre> <p>Here's a full example of what I believe you need. Note that subscribtion to route params should be unsubscribed manually</p> <pre><code>export class ChildComponent implements OnInit, OnDestroy { private sub; constructor(private route: ActivatedRoute) {} ngOnInit() { // Subscribe to router params observable this.sub= this.route.parent.params.subscribe( param =&gt; { let lang = param['lang']; console.log(lang); // Call method or something this.translateThis(lang); }); } ngOnDestroy() { // Unsubscribe from router params observable this.sub.unsubscribe(); } translateThis(lang: any) { // Do your thing here // this.translate.use(lang); } } </code></pre>
How to display waiter while resolving data in Angular 2.0.0? <p>I've project based on Angular 2.0.0, and I want to display waiter (gif or text) while navigating routes, which must resolve data like this:</p> <pre><code> { path: 'profile', loadChildren: () =&gt; System.import('../profile/profile.module'), resolve: { profile: ProfileResolver }, }, </code></pre> <p>Also, preloader need to be applied to every route in project. Thanks.</p>
<p>I'd say you can create a service which would keep eye on routing events and based on <code>NavigationStart</code> &amp; <code>NavigationEnd</code> event it will <code>show/hide</code> loading based on <code>isLoading</code> flag value with combination of <code>[hidden]</code>.</p> <p><strong>Code</strong></p> <pre><code>isLoading: bool = false; constructor(router:Router) { router.events.subscribe(event:Event =&gt; { if(event instanceof NavigationStart) { this.isLoading = true; } if(event instanceof NavigationCancel || event instanceof NavigationError) { this.isLoading = false; } } } </code></pre>
Naming the clusters of leaflet by unigue names like A, B,C instead of numbers <p>I have been trying to name the clusters of leaflet by unique name, can any one give the solution for this ?</p> <p>Context: I have some location pointers, where it get clustered into 5, 3, 4, 3 at some zoom level, instead of showing the numbers on clusters, i need to show by unique name like A for 5, B for 3, C for 4, D for 3 </p>
<p>Starting from the <a href="http://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-custom.html" rel="nofollow">custom cluster example</a>, you can think of something along those lines:</p> <pre><code>var alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); var n = -1; var markers = L.markerClusterGroup({ maxClusterRadius: 120, iconCreateFunction: function (cluster) { n++; return L.divIcon({ html: alphabet[n], className: 'mycluster', iconSize: L.point(40, 40) }); }, }); </code></pre> <p>It will only work for 26 unique names of course, but you get the idea.</p>
Avoiding primary key constraint violation when using timestamp as the primary key <p>I have a database table where the primary key is defined as a timestamp. The application inserts records to the database based on a certain event that is triggered and the timestamp used will be the one that created this instance. Since this application is running on multiple servers and that event is triggering at the same time in more than one of these servers at the same time, in some cases, the data doesn't get inserted to the database due to the primary key violation. </p> <p>What could I possible change in order to avoid this situation? The ideas that I have at the moment are, </p> <ol> <li><p>Waiting a random time before executing the database insertion. </p> <pre><code>Random r = new Random(); long time = r.nextLong() % 1000; time = time &lt; 0 ? -time : time; // making sure that the waiting time is positive try { Thread.sleep(time); } catch (InterruptedException e) { throw new CustomeException(e); } Table1DataAccess.getInstance().insert(new Date(), "some description"); // inserting data into the table which has two fields. </code></pre></li> <li><p>Making the primary key a composite one.</p></li> </ol> <p>Neither of them seems like good solutions to me, could anyone point me in the right direction?</p> <p>P.S. The table to which I tried inserting data had the timestamp column in <code>Date</code> type and I guess it only has it's precision down to seconds. When I used the type <code>timestamp</code> instead, it offered a default precision of microseconds and it can offer nanoseconds at maximum. </p>
<p>Do not use timestamp as primary key field.</p> <p>Use Integer or BigInt for primary key auto increment fields</p>
apache Ivy authentication with artifactory <p>I have shared repository in artifactory which requires authentication in order to resolve/retrieve dependencies.</p> <p>For some reason Ivy is not able to authenticate.</p> <p>my ivysettings.xml:</p> <pre><code>&lt;ivysettings&gt; &lt;settings defaultResolver="main" /&gt; &lt;credentials host="localhost" realm="Artifactory Realm" username="admin" passwd="password" /&gt; &lt;resolvers&gt; &lt;chain name="main"&gt; &lt;ibiblio name="public" m2compatible="true" root="http://localhost:8081/artifactory/repo" /&gt; &lt;/chain&gt; &lt;/resolvers&gt; &lt;/ivysettings&gt; </code></pre> <p>log file:</p> <pre><code>try to get credentials for: Authenticate Artifactory@localhost authentication: k='Authenticate Artifactory@localhost' c='null' HTTP response status: 401 url=https://localhost/artifactory/repo... the rest of the log file... </code></pre> <p>Artifacotry is configured to authenticate against ldap/active directory</p>
<p>in my configuration realm="Artifactory Realm" was wrong. It should be: realm="Authenticate Artifactory"</p>
How to run a zeppelin notebook using REST api and return results in python? <p>I am running a zeppelin notebook using the following REST call from python:</p> <p><code>import requests requests.post('http://x.y.z.x:8080/api/notebook/job/2BZ3VJZ4G').json()</code></p> <p>The output is {u'status': u'OK'}</p> <p>But I want to return some results/exception(if any) from few blocks in the zeppelin notebook to the python script. </p> <p>I also tried to run only a paragraph in the notebook using </p> <pre><code>requests.post('http://x.y.z.x:8080/api/notebook/job/2BZ3VJZ4G/20160922-140926_526498241').json() </code></pre> <p>and received the same output {u'status': u'OK'}. </p> <p>Can somebody help me to retrieve the results from zeppelin in python?</p>
<p>Zeppelin has introduced a synchronous API to run a paragraph in its latest yet to be releases 0.7.0 version. You can clone the latest code form their repo and build a snapshot yourself. URL for API is <a href="http://[zeppelin-server]:[zeppelin-port]/api/notebook/run/[notebookId]/[paragraphId]" rel="nofollow">http://[zeppelin-server]:[zeppelin-port]/api/notebook/run/[notebookId]/[paragraphId]</a>. This will return output of the paragraph after it has run completely.</p>
Laravel count # of results from whereHas <p>I have the below relationship. <code>User-&gt;hasMany(Posts)</code> and <code>User-&gt;belongsToMany(Following)</code>. Now i want to retrieve the following. Get all the following users of a user that have a specific type of <code>post</code>. I have come so far</p> <pre><code>$writers = $user -&gt;following() -&gt;with('posts') -&gt;whereHas('posts' ,function($query){ $query-&gt;where('type','article'); }) -&gt;get(); </code></pre> <p>Which is ok and returns only the Users that have at least 1 article type post. What i want here is to also in the response</p> <pre><code>{ "id": 37, "name": "Telis Xrysos", "email": "txrysos@mail.com", "url": "", "personal_quote": "", "profile_image_url": "/assets/images/user-no-image.jpg", "private": "0", "posts": [ { "id": 238, "description": "This is Tony Montana #Tony #Montana", "source": "Tony Montana Quote", "image_url": null, "type": "article", "likes": 0, "comments": 0, "user_id": 37, "created_at": "2016-10-11 16:26:28" } ] } </code></pre> <p>To include a count of how many of his posts are articles. I could do a count afterwards at the <code>posts</code> attribute although that is just temporary and will be removed afterwards.</p> <p>I have tried this but all i get is an extra attribute for each user <code>articles_count = []</code></p> <pre><code>public function articlesCount() { return $this-&gt;posts()-&gt;selectRaw('id, count(*) as aggregate')-&gt;where('type','article')-&gt;groupBy('id'); } $writers = $user -&gt;following() -&gt;with('posts') -&gt;with('articlesCount') -&gt;whereHas('posts' ,function($query){ $query-&gt;where('type','article'); }) -&gt;get(); </code></pre>
<p>i'm simply put a custom attribute in Eloquent</p> <pre><code> protected $appends = ['ArticleCount']; public function getArticleCountAttribute(){ return $this-&gt;posts-&gt;count(); } </code></pre> <p>don't forget the relationship too : </p> <pre><code>public function posts(){ return $this-&gt;hasMany('app\posts','id_user','id'); } </code></pre>
Does the echo command append any extra character when writing to text file? <p>I am trying to create a shortcut using batch file. I mimic the following manual steps to do that, but although the manually created file works properly as a shortcut, the shortcut created by batch files command line command does not work-</p> <p>Creating shortcuts manually:</p> <ol> <li>Create a text file</li> <li><p>Add following content to the text file and save:</p> <pre><code>[InternetShortcut] URL=file:///D:\Logs </code></pre></li> <li>Rename the text file to have .url extension.</li> </ol> <p>That process creates a shortcut to D:\Logs directory.</p> <p>Now I do the following to create shortcut using Batch file-</p> <pre><code>( ECHO [InternetShortcut] ECHO URL=file:///D:\Logs ) &gt; E:\myshortcut.url </code></pre> <p>But the shortcut does not work. I checked the contents and they look exactly as what I have in the manually created file.</p> <p>So what is the difference between those manually created and batch file created files?</p>
<p>This works for me:</p> <pre><code>echo [InternetShortcut]&gt; E:\myshortcut.url echo URL=file:///D:\Logs&gt;&gt; E:\myshortcut.url </code></pre> <p>Note that you must <strong>not</strong> have a space before the redirection <code>&gt;</code> or <code>&gt;&gt;</code> because that <em>will</em> be echoed into the file.</p>
Randomizing without duplicating multiple times <p>I have the following task to perform. I get a string which I must write in reverse and also randomize the words in order to form 5 different strings. I have mananged to write the string in reverse and randomize the words, but I'm not able to do it 5 times. Here is the code.</p> <pre><code>var x = "Lorem ipsum dolor sit amet"; var wordsArray = x.split(" "); function wordsReverse(allWords){ var otherArray = []; for ( var i = allWords.length-1; i &gt;= 0; i--) { otherArray.push(allWords[i]); } return otherArray; } function createRandomText(text){ var randomArray = []; var randomText = null; for ( var j = 0; j &lt; 5; j++) { for ( var k = 0; k &lt; text.length; k++) { randomText = text[Math.floor(Math.random()*text.length)]; if ( text[randomText] === undefined ) { randomArray.push(randomText); text[randomText] = true; } } } return randomArray; } console.log(wordsReverse(wordsArray).toString().replace(/\,/g, ' ')) console.log(createRandomText(wordsArray).toString().replace(/\,/g, ' ')) </code></pre> <p>Appreciate the help.</p>
<p>Loop it until you get all 5 random string. If string is not in array loop back.</p> <pre><code>var randomArray = []; While(randomArray.length != 5){ wordsReverse(wordsArray).toString().replace(/\,/g, ' '); var str = createRandomText(wordsArray).toString().replace(/\,/g, ' '); if(randomArray.indexOf(str) &lt; -1) { randomArray.push(str); } } </code></pre>
how can I answer and reject phone call programmatically in android <p>I need to answer and reject phone call programmatically in android. How can I do it when my app is running in the background. I used following method but it isn't working when the app runs in background</p> <pre><code>public void answerCall() { Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON); buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK)); GestureRunEvents.this.getApplicationContext().sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED"); } </code></pre>
<p>Create a Broadcast Receiver class like below.</p> <pre><code>public class IncomingCallReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { final TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); telephony.listen(new PhoneStateListener(){ @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); Log.e("CALL STATE", state + ""); if(state == TelephonyManager.CALL_STATE_RINGING) { Toast.makeText(context, "Incoming Call Number : " + incomingNumber, Toast.LENGTH_LONG).show(); System.out.println("incomingNumber : " + incomingNumber); try { Class c = Class.forName(telephony.getClass().getName()); Method m = c.getDeclaredMethod("getITelephony"); m.setAccessible(true); ITelephony telephonyService = (ITelephony) m.invoke(telephony); Log.e("INCOMING", "CALL"); telephonyService.silenceRinger(); telephonyService.endCall(); Log.e("HANG UP", "REJECTING"); } catch (Exception e) { e.printStackTrace(); } } } },PhoneStateListener.LISTEN_CALL_STATE); } } </code></pre> <p>Then in your Manifest file , </p> <pre><code>&lt;receiver android:name=".IncomingCallReceiver" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.PHONE_STATE" /&gt; &lt;/intent-filter&gt; </code></pre> <p></p> <p>Insert needed permissions too.</p> <pre><code>&lt;uses-permission android:name="android.permission.READ_PHONE_STATE" /&gt; &lt;uses-permission android:name="android.permission.CALL_PHONE" /&gt; &lt;uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" /&gt; </code></pre>
Chart js: hide some labels in the legend <p>Is it any way to hide some labels from the legend in <code>chart js</code>?</p> <p>I know, that I can hide all legend, using this option: <code> legend: { display: false } </code> but I need to hide just a part of labels in the legend.</p>
<p>I've found an answer. It is possible to generate new labels, using <code>generateLabels</code> function such like this:</p> <pre><code>legend: { labels: { generateLabels: function(chart) { return [ { text: 'text', fillStyle: 'red' } ] } } } </code></pre>
I want to compile the __init__.py file and install into other folder in yocto build system? <p>I want to compile the __init__.py file and install into other folder in yocto build system?</p> <p>Scenario:</p> <blockquote> <p>This basically in yocto build system. Third party library as zipped file is available in download folder in my yocto build system. But that library does not have the __init__.py file in the main folder. During the building using bitbake command. It is unpacked and put the working directory and the compile it. But __init__py and __init__.pyc file is not available.</p> </blockquote> <p>Any one have idea, how can I manually copy this __init__.py file and compile using .bb file in yocto builds system? </p>
<p>You can place empty file <strong>__init__.py</strong> along with recipe and add it to <strong>SRC_URI</strong> in this recipe:</p> <pre><code>SRC_URI = "http://www.aaa/bbb.tar.gz \ file://__init__.py" </code></pre> <p>unpacker will just copy it to WORKDIR where the archive is unpacked.</p>
ckeditor set custom skinpath <p>I have a problem with the CKEDITOR. I installed it with bower and changed the basepath. So CKEDITOR works. My problem now is to laod a custom skin, because i download it also with bower.</p> <p>This is the code:</p> <pre><code>&lt;textarea id="editor-&lt;?= $block_count ?&gt;" name="block[&lt;?= $block_count ?&gt;][text][]" rows="10" cols="80" class="form-control"&gt;&lt;/textarea&gt; &lt;script&gt; CKEDITOR.replace('editor-&lt;?= $block_count ?&gt;',{ customConfig: '../../dist/scripts/ckeditor.js', skin: 'office2013' }); &lt;/script&gt; </code></pre> <p>But if it want to laod the skin i get this error message:</p> <pre><code>ckeditor.js:76 GET htttp://myurl.com/src/bower_components/ckeditor/skins/office2013/editor.css?t=G87D </code></pre> <p>Can i define a skinpath to load it from teh bower path like:</p> <pre><code>CKEDITOR.replace('editor-&lt;?= $block_count ?&gt;',{ customConfig: '../../dist/scripts/ckeditor.js', skinpath: 'src/bower_componnts/ckeditor-office2013-skin/office2013/', skin: 'office2013' }); </code></pre>
<p>Yes you can. <a href="http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-skin" rel="nofollow">Check the documentation</a>. Quoting docs:</p> <blockquote> <p>It is possible to install skins outside the default skin folder in the editor installation. In that case, the absolute URL path to that folder should be provided, separated by a comma ('skin_name,skin_path').</p> </blockquote> <pre><code>config.skin = 'moono'; config.skin = 'myskin,/customstuff/myskin/'; </code></pre> <p>So, something similar should do the trick:</p> <pre><code>skin: 'office2013,/src/bower_components/ckeditor-office2013-skin/office2013/' </code></pre>
Working with RadioButtonList in UserControl in jQuery <p>The below is the code in jQuery. </p> <pre><code>$(document).ready(function(){ $("[id^='rdlAvailability_'][type='radio']").each(function () { $(this).change(function(){ var radioBtnId = this.id; var $this = $(this); radconfirm('Are you sure you want to select this slot?', function(arg){ if (arg == true) { $find('&lt;%= FindControl("txtAvailability").ClientID %&gt;').set_value(""); } else { $this.siblings('input').prop('checked',true); var rdlAvailability = document.getElementById(radioBtnId); rdlAvailability.checked = false; $this.prop('checked', false); } }, 300, 100,""); }) }); </code></pre> <p>});</p> <p>This is the markup for rdlAvailability for Monday</p> <pre><code>&lt;table id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability" class="radio1" border="0" style="color: #004B59; font-size: 11px; font-family: Arial, Sans-serif; text-align: justify"&gt; &lt;tr&gt; &lt;td&gt;&lt;span disabled="disabled"&gt;&lt;input id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_0" type="radio" name="ctl00$ContentPlaceHolder1$MyAvailability$MyAvailabilityMonday$rdlAvailability" value="AVL01" disabled="disabled" /&gt;&lt;label for="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_0"&gt;Slot 0&lt;/label&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;input id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_1" type="radio" name="ctl00$ContentPlaceHolder1$MyAvailability$MyAvailabilityMonday$rdlAvailability" value="AVL02" /&gt;&lt;label for="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_1"&gt;Slot 1&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;input id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_2" type="radio" name="ctl00$ContentPlaceHolder1$MyAvailability$MyAvailabilityMonday$rdlAvailability" value="AVL03" /&gt;&lt;label for="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_2"&gt;Slot 2&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;input id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_3" type="radio" name="ctl00$ContentPlaceHolder1$MyAvailability$MyAvailabilityMonday$rdlAvailability" value="AVL04" checked="checked" /&gt;&lt;label for="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_3"&gt;Slot 3&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>How can I make the jQuery code to work only for single time when click on Monday or any day. I have given the markup for Monday. Now I am getting 4 confirmation message boxes with this. It is not catching the right Availability Id of <code>rdlAvailability</code>.</p>
<p>Try binding the click directly and not in each function</p> <pre><code>$("[id^='rdlAvailability_'][type='radio']").on("change", function() { // your code here }); </code></pre>
selenium.common.exceptions.WebDriverException: Message: Service <p>I had a trouble when i use selenium to control my Chrome. Here is my code:</p> <pre><code>from selenium import webdriver driver = webdriver.Chrome() </code></pre> <p>When i tried to operate it ,it runs successfully at first,the Chrome pop on the screen. However, it shut down at the few seconds. <a href="https://i.stack.imgur.com/EbQE7.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/EbQE7.jpg" alt="Here is the Traceback information"></a></p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#3&gt;", line 1, in &lt;module&gt; driver = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\chrome.exe') File "C:\Users\35273\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__ self.service.start() File "C:\Users\35273\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 86, in start self.assert_process_still_running() File "C:\Users\35273\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 99, in assert_process_still_running % (self.path, return_code) selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\Google\Chrome\chrome.exe unexpectedly exited. Status code was: 0 </code></pre>
<p>You need to provide the path of chromedriver...download from <a href="http://chromedriver.storage.googleapis.com/index.html?path=2.24/...unzip" rel="nofollow">http://chromedriver.storage.googleapis.com/index.html?path=2.24/...unzip</a> it and provide path to it in... webdriver.chrome ("path to chromedriver")</p> <p>I explain the things here:</p> <pre><code>from selenium import webdriver driver = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe") </code></pre> <p>This is the error if i run the above code:</p> <pre><code> C:\Python27\python.exe C:/Users/Gaurav.Gaurav-PC/PycharmProjects/Learning/StackOverflow/SeleniumQuestion/test123.py Traceback (most recent call last): File "C:/Users/Gaurav.Gaurav-PC/PycharmProjects/Learning/StackOverflow/SeleniumQuestion/test123.py", line 4, in &lt;module&gt; driver = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe") File "C:\Python27\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__ self.service.start() File "C:\Python27\lib\site-packages\selenium\webdriver\common\service.py", line 86, in start self.assert_process_still_running() File "C:\Python27\lib\site-packages\selenium\webdriver\common\service.py", line 99, in assert_process_still_running % (self.path, return_code) selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\Google \Chrome\Application\chrome.exe unexpectedly exited. Status code was: 0 </code></pre> <p>Which is same as mentioned by @Weiziyoung in original problem.</p> <p>The solution is as I mentioned you need to provide the path to chromedriver in place of chrome browser like</p> <pre><code>driver = webdriver.Chrome("E:\Jars\chromedriver.exe") </code></pre> <p>It will resolve the problem</p>
Caliburn Micro ViewLocator with different namespace <p>I'm using Caliburn Micro for MVVM. Now I have the following situation. I have a UserControl with View and ViewModel in my first assembly <code>assembly1</code> in <code>namespace1</code>. If I use it in an second assembly <code>assembly2</code> that has the same namespace <code>namespace1</code> (it´s in the same solution) everything works fine.</p> <p>Now I'd like to use my ViewModel in another <code>Solution</code> with namespace <code>namespace3</code>. If I try this I always get the error, that View couldn't be located.</p> <p>I build up a workaround that sets the Binding manually in the bootstrapper (using Ninject).</p> <pre><code>protected override void Configure() { _kernel = new StandardKernel(); _kernel.Bind&lt;OverlayManagerView&gt;().To&lt;OverlayManagerView&gt;().InSingletonScope(); _kernel.Bind&lt;OverlayManagerViewModel&gt;().To&lt;OverlayManagerViewModel&gt;().InSingletonScope(); base.Configure(); } protected override void OnStartup(object sender, System.Windows.StartupEventArgs e) { ViewModelBinder.Bind(IoC.Get&lt;OverlayManagerViewModel&gt;(), IoC.Get&lt;OverlayManagerView&gt;(), null); ... } </code></pre> <p>This is working, but if I'd like to use my ViewModels from <code>assembly1</code> I won't always set the Binding manually and as Singleton. </p> <p>Is there a way to tell the <code>Caliburn ViewLocator</code> that Views might be at a different namespace?</p> <p>I tried following not working...</p> <pre><code> ViewLocator.AddNamespaceMapping("namespace1", "namespace3"); ViewLocator.AddNamespaceMapping("namespace1", "namespace1"); ViewLocator.AddNamespaceMapping("namespace3", "namespace1"); </code></pre> <p>Maybe someone knows a solution.</p>
<p>In your <code>Configure</code>method you should use :</p> <pre><code>ViewLocator.AddSubNamespaceMapping("ViewModelsNamespace", "ViewsNamespace"); </code></pre> <p>and you have to override the following method :</p> <pre><code> protected override IEnumerable&lt;Assembly&gt; SelectAssemblies() { var assemblies = new List&lt;Assembly&gt;(); assemblies.AddRange(base.SelectAssemblies()); //Load new ViewModels here string[] fileEntries = Directory.GetFiles(Directory.GetCurrentDirectory()); assemblies.AddRange(from fileName in fileEntries where fileName.Contains("ViewModels.dll") select Assembly.LoadFile(fileName)); assemblies.AddRange(from fileName in fileEntries where fileName.Contains("Views.dll") select Assembly.LoadFile(fileName)); return assemblies; } </code></pre> <p>in order to let Caliburn know about your new dlls.</p>
How to create Transparent text in pdfBOX or add opacity to the text with the help of pdfBOX? <p>I am not getting how to add transparent text with the help of pdfBOX.</p>
<p>Here's something that shows alpha with 1.8 (you should use 2.*, that is a bit easier).</p> <pre><code> PDExtendedGraphicsState gs1 = new PDExtendedGraphicsState(); gs1.setNonStrokingAlphaConstant(1f); PDExtendedGraphicsState gs2 = new PDExtendedGraphicsState(); gs2.setNonStrokingAlphaConstant(0.2f); Map&lt;String, PDExtendedGraphicsState&gt; graphicsStatesMap = page.getResources().getGraphicsStates(); if (graphicsStatesMap == null) { graphicsStatesMap = new HashMap&lt;String, PDExtendedGraphicsState&gt;(); } graphicsStatesMap.put("gs1", gs1); graphicsStatesMap.put("gs2", gs2); page.getResources().setGraphicsStates(graphicsStatesMap); cs.setFont(PDType1Font.HELVETICA_BOLD, 60); cs.setNonStrokingColor(255, 0, 0); cs.appendRawCommands("/gs1 gs\n"); cs.beginText(); cs.moveTextPositionByAmount(50, 600); cs.drawString("Apache PDFBox 1"); cs.endText(); cs.setNonStrokingColor(0, 0, 255); cs.appendRawCommands("/gs2 gs\n"); cs.beginText(); cs.moveTextPositionByAmount(70, 620); cs.drawString("Apache PDFBox 2"); cs.endText(); cs.close(); </code></pre>
How to create user module at run-time? <p>I have different set of math expressions that must be evaluated at run-time. Currently the task is done by replacing symbols with equivalent values and <code>eval</code> the result. (could be done by any existing symbolic packages)</p> <p>Now, refer to the definition of modules in Julia-lang:</p> <blockquote> <p>Modules in Julia are separate variable workspaces, i.e. they introduce a new global scope .... Modules allow you to create top-level definitions (aka global variables) without worrying about name conflicts when your code is used together with somebody else’s.</p> </blockquote> <p>And with the power of Julia to do meta-things,<br> I'm wondering if it is possible to create anonymous modules at run-time <code>m=Module()</code>, and use them as a scope to evaluate expressions <code>eval(m, :(a+b))</code>.<br> But I simply can't find a way to load variable into the run-time modules. Although I could get result with:</p> <pre><code>julia&gt; ex=:(module mo; a=1; b=4; end) julia&gt; eval(ex) julia&gt; eval(mo,:(a+b)) </code></pre> <p>I prefer more functional way, using anonymous modules.<br> Any Help.</p>
<p>This works:</p> <pre><code>julia&gt; m=Module() anonymous julia&gt; eval(m, :(a=5)) 5 julia&gt; m.a 5 julia&gt; eval(m, :(a)) 5 julia&gt; eval(m, :(2a)) 10 </code></pre>
Exception while trying to read file usin PCLStorage from PCL project <p>I am trying to get file from <code>PCL</code> project using <code>PCLStorage</code> as below. I am using Xamarin in Visual Studio 2015 Professional.</p> <pre><code>IFile file = await FileSystem.Current.GetFileFromPathAsync("file\path"); </code></pre> <p>But I am getting exception as:</p> <blockquote> <p>System.NotImplementedException: This functionality is not implemented in the portable version of this assembly. You should reference the PCLStorage NuGet package from your main application project in order to reference the platform-specific implementation.</p> </blockquote>
<p>You need to add the PCLStorage NuGet to both your PCL and your platform specific project.</p> <p>So if you have the following solution:</p> <pre><code>PCL Android iOS </code></pre> <p>You would need to add it to all of them:</p> <pre><code>PCL PCLStorage Android PCLStorage iOS PCLStorage </code></pre> <p>Why? Because the NuGet uses the bait and switch technique, where the PCL contains a simple facade with the bait. At runtime this gets switched out with platform specific implementation.</p>
setContentView in retrofit response success doesn't show all the information in scroll? <p>I'm using retrofit and coordinatorlayout. All seems that work fine but I'm getting a small problem. That I want to do is that the layout will display in the moment that the response is success. For this reason, I'm calling the setContentView inside the response (I don't know if this is a good practice or not)</p> <p>My problem is that this works, but the layout don't do the scroll in all the information. He cut the last lines of text. If I call the setContentView in the oncreate method the scroll in the coordinatorlayout is ok (show all the information) but in this scenario I can see the layout design before all the correct images and text when finish the success response.</p> <p>Somebody know how can I fix this problem??</p> <p>Thanks in advance</p> <p>Detail Class:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); apiCall(R.layout.detail); } private void apiCall(final int layout){ Bundle extras = getIntent().getExtras(); if (extras != null) { id = extras.getString("id"); } ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); Call&lt;Hostel&gt; call = apiService.getHostelId(id); call.enqueue(new Callback&lt;Hostel&gt;() { @Override public void onResponse(Call&lt;Hostel&gt; call, Response&lt;Hostel&gt; response) { try { if (response.code() == 200) { setContentView(layout); initView(response); setToolbar(); } else { Toast.makeText(getApplication(), getResources().getString(R.string.no_conexion), Toast.LENGTH_SHORT).show(); } }catch (Exception e){ Log.e(TAG, e.toString()); } } @Override public void onFailure(Call&lt;Hostel&gt; call, Throwable t) { Log.e(TAG, t.toString()); } }); } </code></pre> <p>detail.xml</p> <pre><code>&lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/coordinator" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"&gt; &lt;android.support.v4.widget.NestedScrollView android:id="@+id/scroll" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/app_bar" app:layout_behavior="@string/appbar_scrolling_view_behavior"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingTop="24dp"&gt; &lt;android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="19dp"&gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="10dp" android:paddingBottom="10dp" android:paddingTop="5dp"&gt; &lt;TextView android:id="@+id/propertyName_detail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/description" android:textAppearance="@style/TextAppearance.AppCompat.Title" /&gt; &lt;TextView android:id="@+id/description_detail" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; &lt;android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="19dp" android:layout_marginLeft="19dp" android:layout_marginRight="19dp"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"&gt; &lt;LinearLayout style="@style/Widget.CardContent" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/address_1" android:textAppearance="@style/TextAppearance.AppCompat.Title" /&gt; &lt;TextView android:id="@+id/addres_one_detail" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt; &lt;LinearLayout style="@style/Widget.CardContent" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/address_2" android:textAppearance="@style/TextAppearance.AppCompat.Title" /&gt; &lt;TextView android:id="@+id/addres_two_detail" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt; &lt;LinearLayout style="@style/Widget.CardContent" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/city" android:textAppearance="@style/TextAppearance.AppCompat.Title" /&gt; &lt;TextView android:id="@+id/city_detail" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt; &lt;LinearLayout style="@style/Widget.CardContent" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/county" android:textAppearance="@style/TextAppearance.AppCompat.Title" /&gt; &lt;TextView android:id="@+id/country_detail" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; &lt;android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="19dp"&gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/directions" android:textAppearance="@style/TextAppearance.AppCompat.Title" /&gt; &lt;TextView android:id="@+id/directions_detail" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; &lt;/LinearLayout&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="256dp" android:fitsSystemWindows="true" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"&gt; &lt;android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapser" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:expandedTitleMarginEnd="64dp" app:expandedTitleMarginStart="48dp" app:layout_scrollFlags="scroll|exitUntilCollapsed"&gt; &lt;ImageView android:id="@+id/image_detail" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:scaleType="centerCrop" app:layout_collapseMode="parallax" /&gt; &lt;android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@android:color/transparent" app:layout_collapseMode="pin" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:theme="@style/CustomActionBar" /&gt; &lt;/android.support.design.widget.CollapsingToolbarLayout&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre>
<p>Call <code>setContentView</code> in <code>oncreate</code> just try do show layout to user when response is successful. you can manage it using <code>alpha</code> property of a <code>widget</code></p> <blockquote> <p>android:alpha="0.0" to make view invisible </p> <p>android:alpha="1.0" to make view visible</p> </blockquote> <p>now in <code>oncreate</code> call </p> <pre><code>CoordinatorLayout cL=(CoordinatorLayout)findViewById(R.id.coordinator); cL.setAlpha(0); </code></pre> <p>and after getting successfull response make it <code>visible</code> like this :</p> <pre><code>cL.setAlpha(1); </code></pre>
CSS Image Hover surprisingly not working? <p>I'm trying to create a hover effect that will change the color of the image to blue, as the mouse hovers it. I've already created a class for the images and styled it in my css but its still not working. I've also tried changing z-indexes but to no avail. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code> @import url(http://fonts.googleapis.com/css?family=Black+Ops+One:400,700); /*--- Header --*/ @import url(http://fonts.googleapis.com/css?family=Open+Sans:400,700); /*--- Navigation --*/ * { margin: 0; border: 0; padding: 0; } body { background-image: url('../Images/background.png'); background-repeat: repeat-x; } .clearfix { clear:both; } #wrapper { margin: 0 auto; max-width: 1120px; overflow: auto; border: 1px solid black; } #main_header { width: 100%; font-family: 'Black Ops One', sans-serif; background-color: black; border: 1px solid black; color: white; } #main_header h1 { float: left; font-size: 380%; margin: -10% 0 0 2%; } #callout { margin: 50px 20px 0 0; } #callout h2{ text-align: right; color: white; } #callout p{ text-align: right; padding: 0%; color: grey; font-size: 20px; margin-bottom: 3px; } #nav_menu { width: 100%; height: 10%; background-color: white; } #nav_menu li { display: inline-block; margin: 20px 20px 20px 63px; font-family: 'Open Sans', sans-serif; font-size: 20px; font-weight: bold; } #nav_menu li a { text-decoration: none; color: black; } #nav_menu li a:hover { color: grey; } #content_area { width: 100%; margin: 10px; } .sub-menu { position: absolute; background-color: white; list-style-type: none; width: 5px; display: none; z-index: 60; border-radius: 15px; } #nav_menu .sub-menu li a { color: black; } #nav_menu li:hover .sub-menu { display: block; } #nav_menu li .sub-menu { width: 16.5%; } #nav_menu li .sub-menu li { display: block; margin-left: 20px; } .sub-menu li:hover { color: green; background-color: yellow; } /*--- Start Image Slider --*/ .slider{ max-width: 1100px; box-shadow: 0px 0px 0px 0 rgba(0, 0, 0, 0.07); } .slider1 img{ width: 100%; margin: 0 auto; } .slider .bx-wrapper .bx-controls-direction a{ outline: 0 none; position: absolute; text-indent: -9999px; top: 40%; height: 71px; width: 40px; transition: all 0.7s; } .slider .bx-wrapper:hover .bx-controls-direction a{ } .slider .bx-wrapper .bx-prev{ background: url("../Images/arrow_left.png") no-repeat 7px 9px; left: 0px; } .slider .bx-wrapper .bx-prev:hover{ background: url("../Images/arrow_left.png") no-repeat 8px 15px; } .slider .bx-wrapper .bx-next{ background: url("../Images/arrow_right.png") no-repeat 10px 12px; right: 0px; } .slider .bx-wrapper .bx-next:hover{ background: url("../Images/arrow_right.png") no-repeat 10px 17px; } /*--- End Image Slider --*/ .one-third img{ text-align: center; max-width: 100%; height: auto; opacity: 0.9; } .border_section p{ font-family: 'Lato', sans-serif; padding: 2%; color: white; text-align: justify; } .border_section h3 { font-family: 'Open Sans', sans-serif; text-align: center; color: white; text-transform: uppercase; letter-spacing: 1%; } .border_section { border: 1px solid black; background-color: black; } .one-third { width: 27.35%; float: left; margin: 2% 0 3% 4%; text-align: center; background-color: white; } .guitarLogo img:hover { color: yellow; background-color: blue; } footer{ font-family: 'Open Sans', sans-serif; font-weight: bold; text-align: center; width: 100%; height: 6%; background-color: black; overflow: auto; } footer p { margin-top: 1%; color: white; } </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="border_section"&gt; &lt;img class="guitarLogo" src="../Images/Guitar Brands/ibanezLogo.jpg" runat="server"/&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class="one-third"&gt; &lt;div class="border_section"&gt; &lt;img class="guitarLogo" src="../Images/Guitar Brands/fenderLogo.jpg" runat="server"/&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class="one-third"&gt; &lt;div class="border_section"&gt; &lt;img class="guitarLogo" src="../Images/Guitar Brands/gibsonLogo.jpg" runat="server"/&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class="one-third"&gt; &lt;div class="border_section"&gt; &lt;img class="guitarLogo" src="../Images/Guitar Brands/prsLogo.jpg" runat="server"/&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class="one-third"&gt; &lt;div class="border_section"&gt; &lt;img class="guitarLogo" src="../Images/Guitar Brands/ernieballLogo.jpg" runat="server"/&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class="one-third"&gt; &lt;div class="border_section"&gt; &lt;img class="guitarLogo" src="../Images/Guitar Brands/espLogo.jpg" runat="server"/&gt; &lt;/div&gt; &lt;/section&gt;</code></pre> </div> </div> </p>
<p>If you don't want to affect other elements and change the background color of <code>div</code> element around your images, then create new class like <code>myHover</code> and add existing CSS to it, like:</p> <p><strong>HTML</strong>:</p> <pre><code>&lt;div class="border_section myHover"&gt; &lt;img class="guitarLogo" src="../Images/Guitar Brands/fenderLogo.jpg" runat="server" /&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong>:</p> <pre><code>.myHover:hover { color: yellow; background-color: blue; } </code></pre> <p>JSFiddle example: <a href="https://jsfiddle.net/59drat5e/4/" rel="nofollow">https://jsfiddle.net/59drat5e/4/</a></p>
Regular expression not working in pywinauto unless I give full text <p>Here is the code snippet that I am using:</p> <pre><code>browserWin = application.Application() browserWin.Start(&lt;FirefoxPath&gt;) # This starts the Firefox browser. browserWin.Window_(title_re="\.* Firefox \.*") </code></pre> <p>If I use the expression: ".* Mozilla Firefox Start Page .*", it works. However, if I only use a partial text, it doesn't work. </p> <p>What am I doing wrong here?</p>
<p>Escaped <code>.</code> with "\" means real dot symbol should be at the start of the text. Just remove "\".</p>
How join multiple table <p>I have five tables and i want to retrieve specific details from specifc table using join can you suggest me how to do that?</p> <p>tables:</p> <pre><code>tblPriscriptionDetail tblPriscription tblpatient tblinsuranceplan tblinsurance </code></pre> <p>from those table <code>tblPriscriptionDetail</code> is my main table and <code>tblinsurance</code> is my target table from i want to get <code>insurancename</code>.</p> <p>Flow of table</p> <pre><code>tblinsurance is refer to tblinsuranceplan tblinsuranceplan is refer to tblpatient tblpatient is refere to tblPriscription and last tblPriscription is refere to tblPriscriptionDetail tblPriscriptionDetail : tblPriscription : tblpatient : tblinsuranceplan : tblinsurance </code></pre> <p>Can you tell me that how to do that</p>
<p><strong>Try:</strong></p> <p>Replace <code>*</code> with column names you want to select.</p> <pre><code>SELECT * FROM tblPriscriptionDetail tpd INNER JOIN tblPriscription tpn on tpd.tblPriscriptionId=tpn.tblPriscriptionId INNER JOIN tblpatient tp on tp.tblpatientId = tpn.tblpatientId INNER JOIN tblinsuranceplan tip on tip.tblinsuranceplanid=tp.tblinsuranceplanid INNER JOIN tblinsurance ti on ti.tblinsuranceid=tip.tblinsuranceid </code></pre>
Get json array response and store in another array <p>I have cURL function which make calls to api based on ID which I provide and return data in array. So far everything works perfectly. What I want and can't figure out is this:</p> <p>I have foreach which display in table all orders lie</p> <pre><code>@foreach($orders as $order) $order-&gt;address $order-&gt;time_created $order-&gt;price ... etc @endforeach </code></pre> <p>Is it possible to put this cURL inside the foreach and add on each row based on <code>$order-&gt;order_id</code> to show some more data from the array?</p> <p>So something like this</p> <pre><code>@foreach($orders as $order) $order-&gt;address $order-&gt;time_created $order-&gt;price ... etc $url = get_curl_content_tx("http://example.com/".$order-&gt;order_id); $data = json_decode($url,true); @foreach ( $data as $moreData ) @if ( $moreData['data'] == $order-&gt;time_created ) // show something @else // show other thing @endif @endforeach @endforeach </code></pre> <p>My problem is that I can't figure how to loop the url so I can get all <code>orders_id</code> i.e.</p> <pre><code>$url = get_curl_content_tx("http://example.com/1"); $url = get_curl_content_tx("http://example.com/2"); $url = get_curl_content_tx("http://example.com/3"); $url = get_curl_content_tx("http://example.com/4"); $url = get_curl_content_tx("http://example.com/5"); $url = get_curl_content_tx("http://example.com/6"); </code></pre> <p>So then I can perform my <code>if/else</code> block. Framework which I use is Laravel 4.2. </p> <p>Hope it is clear enough what I want to accomplish. If is not I will try to clear things..</p> <p>EDIT: Example what it should be:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="text-center"&gt;#&lt;/th&gt; &lt;th class="text-center"&gt;Date Created&lt;/th&gt; &lt;th class="text-center"&gt;Name&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;1&lt;/th&gt; &lt;th&gt;$url = get_curl_content_tx("http://example.com/1")&lt;/th&gt; &lt;th&gt;Product 1&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;2&lt;/th&gt; &lt;th&gt;$url = get_curl_content_tx("http://example.com/2")&lt;/th&gt; &lt;th&gt;Product 2&lt;/th&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
<p>You can use laravel's <code>unique</code> method for collections to remove duplicate order id's before iterating them.</p> <pre><code>$collection = collect([ ['name' =&gt; 'iPhone 6', 'brand' =&gt; 'Apple', 'type' =&gt; 'phone'], ['name' =&gt; 'iPhone 5', 'brand' =&gt; 'Apple', 'type' =&gt; 'phone'], ['name' =&gt; 'Apple Watch', 'brand' =&gt; 'Apple', 'type' =&gt; 'watch'], ['name' =&gt; 'Galaxy S6', 'brand' =&gt; 'Samsung', 'type' =&gt; 'phone'], ['name' =&gt; 'Galaxy Gear', 'brand' =&gt; 'Samsung', 'type' =&gt; 'watch'], ]); $unique = $collection-&gt;unique('brand'); $unique-&gt;values()-&gt;all(); </code></pre> <p>Or you can use PHP method as well. <a href="http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php">How to remove duplicate values from a multi-dimensional array in PHP</a></p>
editing a model in more than one view <p>My target is, to modify a model in more than one view. Since sometimes my models have many properties I want to modify them in more than one view. Something like:</p> <p>first page edits 2 properties, second page edits 3 other properties,...</p> <p>the model looks like this:</p> <pre><code>public class LoadViewModel { public int CurrentPage { get; set; } = -1; public PageViewModel PageViewModel { get; set; } } public class PageViewModel { public string Param1 { get; set; } public string Param2 { get; set; } public int Param3 { get; set; } } </code></pre> <p>my view on the Index-page looks like this:</p> <pre><code>@model LoadViewModel @using(Ajax.BeginForm("Load", "Home", new AjaxOptions {UpdateTargetId = "page"}, new {lvm = Model})) { &lt;div id="page"&gt;&lt;/div&gt; &lt;input type="submit"/&gt; } </code></pre> <p>and this is my action:</p> <pre><code>public ActionResult Load(LoadViewModel lvm = null) { if (lvm == null) lvm = new LoadViewModel(); lvm.CurrentPage += 1; TempData["CurrentPage"] = TempData["CurrentPage"] == null ? 0 : (int)TempData["CurrentPage"] + 1; if (!partialViewDict.ContainsKey((int) TempData["CurrentPage"])) TempData["CurrentPage"] = 0; return PartialView(partialViewDict[(int)TempData["CurrentPage"]], lvm); } </code></pre> <p>the pages are just partials that are mapped:</p> <pre><code>private Dictionary&lt;int, string&gt; partialViewDict = new Dictionary&lt;int, string&gt; { {0, "Pages/_Page1"}, {1, "Pages/_Page2"}, {2, "Pages/_Page3"}, }; </code></pre> <p>and designed like this:</p> <pre><code>@using WebApplication1.Controllers @model LoadViewModel @{ TempData["CurrentPage"] = 0; } @Html.DisplayNameFor(m =&gt; m.PageViewModel.Param1) @Html.EditorFor(m =&gt; m.PageViewModel.Param1) </code></pre> <p>this is working. When switching to Page2 the model is correctly set, but when hitting the <code>submit</code> the value of <code>Param1</code> (that I set in Page1) is resetted to <code>null</code> and only the values I set in the current partial are correct.</p> <p>This is Page2:</p> <pre><code>@using WebApplication1.Controllers @model LoadViewModel @{ TempData["CurrentPage"] = 1; } @Html.DisplayNameFor(m =&gt; m.PageViewModel.Param2) @Html.EditorFor(m =&gt; m.PageViewModel.Param2) </code></pre> <p>When I add a <code>@Html.HiddenFor(m =&gt; m.PageViewModel.Param1)</code> into the partial, the value is still set. But I don't want the values to be resetted. I don't want to add an <code>@Html.HiddenFor</code> for all properties a set in a previous view. How can I prevent that the values are resetted when hitting <code>submit</code> without adding <code>@Html.HiddenFor</code> for all not listed attributes? Or is there any other possibility to catch my target?</p>
<p>There's two pieces to this. First, the post itself, and getting that to validate. For that, each step should have its own view model, containing only the properties it's supposed to modify. This allows you to add all the validation you need without causing other steps to fail. In the end, you'll combine the data from all of these into your entity class or whatever.</p> <p>Which brings us to the second piece. You need some way of persisting the data from each step. The only data that will exist after a POST is the data that was posted and anything in the session (which includes <code>TempData</code>). You could always create a bunch of hidden fields to store the data from the previous steps, but that can get a little arduous. Most likely, you'll just want to use the session.</p> <p><code>TempData</code> is basically a specialized instance of <code>Session</code>, so which you use doesn't really matter. With <code>TempData</code>, you'll need to remember call <code>TempData.Keep()</code> for each of the keys you've set for each step or you'll lose the previous steps on the next request. <code>Session</code> will keep them around for the life of the session, but you should remember to remove the keys at the end with <code>Session.Remove()</code>.</p>
How to apply filter to get elements which have same value in JSONobjects inside JSON array using AngularJS <p>I have a JSON array with multiple(dynamic) JSON objects. I need to compare the objects and pick the keys which has the same value in all the objects. My JSON looks like,</p> <pre><code>[ { "CreateAccountName":"Joseph", "CreateDateTime":"0001-01-01T00:00:00", "Description":"Utilization of services", "Type":2, "Id":1000000001, "Count":1, "ModifiedAccountName":"", "ModifiedDateTime":"2016-10-04T10:16:40.5190025", "Name":"Utilization of services", "CardCount":0, "Target":95, "UniversalId":"SDFOPIJ-SDFGLKJ-ER234-234LF", "AccountId":0, "AccountName":"Joseph" }, { "CreateAccountName":"Joseph", "CreateDateTime":"0001-01-01T00:00:00", "Description":"Utilization of Food", "Type":2, "Id":1000000001, "Count":1, "ModifiedAccountName":"", "ModifiedDateTime":"2016-10-04T10:16:40.5190025", "Name":"Utilization of Food", "CardCount":0, "Target":95, "UniversalId":"SDFOPIJ-SDFGLKJ-ER234-234LF", "AccountId":0, "AccountName":"Joseph" }, { "CreateAccountName":"Joseph", "CreateDateTime":"0001-01-01T00:00:00", "Description":"Utilization of services", "Type":2, "Id":1000000001, "Count":1, "ModifiedAccountName":"", "ModifiedDateTime":"2016-10-04T10:16:40.5190025", "Name":"Utilization of services", "CardCount":0, "Target":95, "UniversalId":"SDFOPIJ-SDFGLKJ-ER234-234LF", "AccountId":0, "AccountName":"Joseph" } ] </code></pre> <p>I want to get the Keys which has same value. Example, CreateAccountName. It has same value in all the objects. </p> <p>The tricky case is, the key itself dynamic. I cannot hardcode the key and do compare. The key name may change or another set of keys may come. I am looking for a generic solution to compare and get the "intersection" of the objects. </p>
<p>You can do this just with <code>Array.reduce()</code></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var json = [ { "CreateAccountName":"Joseph", "CreateDateTime":"0001-01-01T00:00:00", "Description":"Utilization of services", "Type":2, "Id":1000000001, "Count":1, "ModifiedAccountName":"", "ModifiedDateTime":"2016-10-04T10:16:40.5190025", "Name":"Utilization of services", "CardCount":0, "Target":95, "UniversalId":"SDFOPIJ-SDFGLKJ-ER234-234LF", "AccountId":0, "AccountName":"Joseph" }, { "CreateAccountName":"Joseph", "CreateDateTime":"0001-01-01T00:00:00", "Description":"Utilization of Food", "Type":2, "Id":1000000001, "Count":1, "ModifiedAccountName":"", "ModifiedDateTime":"2016-10-04T10:16:40.5190025", "Name":"Utilization of Food", "CardCount":0, "Target":95, "UniversalId":"SDFOPIJ-SDFGLKJ-ER234-234LF", "AccountId":0, "AccountName":"Joseph" }, { "CreateAccountName":"Joseph", "CreateDateTime":"0001-01-01T00:00:00", "Description":"Utilization of services", "Type":2, "Id":1000000001, "Count":1, "ModifiedAccountName":"", "ModifiedDateTime":"2016-10-04T10:16:40.5190025", "Name":"Utilization of services", "CardCount":0, "Target":95, "UniversalId":"SDFOPIJ-SDFGLKJ-ER234-234LF", "AccountId":0, "AccountName":"Joseph" } ]; var intersection = json.reduce(function(result, item) { Object.keys(result).forEach(function(key) { if(! item.hasOwnProperty(key) || item[key] !== result[key]) delete result[key]; }); return result; }); console.log(intersection)</code></pre> </div> </div> </p>
ZingChart get crosshair position on click <p>The ZingChart <code>click</code> event states that the callback will receive an object. The <code>x</code> attribute will contain </p> <blockquote> <p>The x position of the click relative to the chart position</p> </blockquote> <p>I assume this is the cursor position in the window (i.e. pixels) relative to the position (top left corner?) of the div element that contains the graph.</p> <p>Is there a way to get the "X" value of the crosshair position upon click as illustrated in the picture: <a href="https://i.stack.imgur.com/WXdyf.png" rel="nofollow">Example</a></p> <p>i.e. if the crosshair is at "0", I want to get that value upon click. When I use the <code>arg.x</code> of the click event, and the crosshair is at "0" I get 49, and I need 0.</p> <p>The code:</p> <pre><code>var values = [0,2.81,5.61,8.38, ...] var chartData={ "type":"line", // Specify your chart type here. "background-color":"#f4f4f4", "scale-x": { "zooming":true }, "plot": { // "mode":"fast", "exact":true, // "smartSampling":true, // "maxNodes":0, // "maxTrackers":0, "lineWidth":2, "shadow":false, "marker":{ "type":"none", "shadow":false } }, "plotarea":{ "background-color":"#fbfbfb", "margin-top":"30px", "margin-bottom":"40px", "margin-left":"50px", "margin-right":"30px" }, "scaleX":{ "autoFit":true, "zooming":true, "normalize":true, "lineWidth":1, "line-color":"#c7c9c9", "tick":{ "lineWidth":1, "line-color":"#c7c9c9" }, "guide":{ "visible":false }, "item":{ "font-color":"#818181", "font-family":"Arial", "padding-top":"5px" }, "maxLabels":10 }, "scrollX":{ }, "scaleY":{ "minValue":"auto", "autoFit":true, "lineWidth":1, "line-color":"#c7c9c9", "tick":{ "lineWidth":1, "line-color":"#c7c9c9" }, "item":{ "font-color":"#818181", "font-family":"Arial", "padding-right":"5px" }, "guide":{ "lineStyle":"solid", "line-color":"#c7c9c9", "alpha":0.2 } }, "tooltip":{ "visible":false }, "crosshairX":{ "lineWidth":1, "line-color":"#003849", "marker":{ "size":4, "type":"circle", "borderColor":"#fff", "borderWidth":1 }, "scale-label":{ "font-color":"#ffffff", "background-color":"#003849", "padding":"5px 10px 5px 10px", "border-radius":"5px" }, // "plotLabel":{ // "multiple":false, // "callout":false, // "shadow":false, // "height":"115px", // "padding":"5px 10px 5px 10px", // "border-radius":"5px", // "alpha":1, // "headerText":"Node %scale-key-text&lt;br&gt;", // "text":"&lt;b&gt;%plot-text:&lt;/b&gt; %node-value" // } }, "series":[ // Insert your series data here. { "text": "P1", "values": values, "line-color":"#7ca82b", "line-width":1 }, ] }; zingchart.render({ // Render Method[3] id:'id_graph_box', data:chartData, height:400, width:800, }); zingchart.click=function(p) { console.log("GRAPH CLICKEND ON X:", p) </code></pre>
<p>Full disclosure, I'm a member of the ZingChart team. </p> <p>Yes the values are relative the chart position. What you can do is use our API methods to get the chart information you need based on the xy location of the click. You will use <a href="https://www.zingchart.com/docs/api/api-methods/#zingchart__exec__api__getxyinfo" rel="nofollow">getxyinfo</a>, which will grab an array of information about the chart. It will grab scale information closest to where the click happened. This means if you click in between two nodes (for scale-x), whichever is closest to (x position from click) it will give you that information. The crosshair/guide works the same way when highlighting nodes, so this shouldn't be a problem. I just thought it was relevant to bring up.</p> <p>The demo below looks a little funky with the console.log() output. <a href="http://demos.zingchart.com/view/0JGE5PDV" rel="nofollow">Here</a> is a link hosted by us as well. <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var values = [0,2.81,5.61,8.38]; var chartData = { "type":"line", // Specify your chart type here. "background-color":"#f4f4f4", "scale-x": { "zooming":true }, "plot": { // "mode":"fast", "exact":true, // "smartSampling":true, // "maxNodes":0, // "maxTrackers":0, "lineWidth":2, "shadow":false, "marker":{ "type":"none", "shadow":false } }, "plotarea":{ "background-color":"#fbfbfb", "margin-top":"30px", "margin-bottom":"40px", "margin-left":"50px", "margin-right":"30px" }, "scaleX":{ "autoFit":true, "zooming":true, "normalize":true, "lineWidth":1, "line-color":"#c7c9c9", "tick":{ "lineWidth":1, "line-color":"#c7c9c9" }, "guide":{ "visible":false }, "item":{ "font-color":"#818181", "font-family":"Arial", "padding-top":"5px" }, "maxLabels":10 }, "scrollX":{ }, "scaleY":{ "minValue":"auto", "autoFit":true, "lineWidth":1, "line-color":"#c7c9c9", "tick":{ "lineWidth":1, "line-color":"#c7c9c9" }, "item":{ "font-color":"#818181", "font-family":"Arial", "padding-right":"5px" }, "guide":{ "lineStyle":"solid", "line-color":"#c7c9c9", "alpha":0.2 } }, "tooltip":{ "visible":false }, "crosshairX":{ "lineWidth":1, "line-color":"#003849", "marker":{ "size":4, "type":"circle", "borderColor":"#fff", "borderWidth":1 }, "scale-label":{ "font-color":"#ffffff", "background-color":"#003849", "padding":"5px 10px 5px 10px", "border-radius":"5px" }, // "plotLabel":{ // "multiple":false, // "callout":false, // "shadow":false, // "height":"115px", // "padding":"5px 10px 5px 10px", // "border-radius":"5px", // "alpha":1, // "headerText":"Node %scale-key-text&lt;br&gt;", // "text":"&lt;b&gt;%plot-text:&lt;/b&gt; %node-value" // } }, "series":[ // Insert your series data here. { "text": "P1", "values": values, "line-color":"#7ca82b", "line-width":1 }, ] }; zingchart.render({ id: 'myChart', data: chartData, height: '100%', width: '100%' }); zingchart.bind('myChart', 'click', function(e) { /* * Returns array of information. * xyInformation[0] -&gt; scale-x info * xyInformation[1] -&gt; scale-y info * xyInformation[2] -&gt; node info */ var xyInformation = zingchart.exec('myChart', 'getxyinfo', { x: e.x, y: e.y }); console.log(xyInformation) });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { height:100%; width:100%; margin:0; padding:0; } #myChart { height:100%; width:100%; min-height:150px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;!--Assets will be injected here on compile. Use the assets button above--&gt; &lt;script src= "https://cdn.zingchart.com/zingchart.min.js"&gt;&lt;/script&gt; &lt;script&gt; zingchart.MODULESDIR = "https://cdn.zingchart.com/modules/"; ZC.LICENSE = ["569d52cefae586f634c54f86dc99e6a9","ee6b7db5b51705a13dc2339db3edaf6d"];&lt;/script&gt; &lt;!--Inject End--&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="myChart"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
Quickly build large dict in elegant manner <p>I have a list with size about 30000: <code>['aa', 'bb', 'cc', 'dd', ...]</code>, from this list, I want to build a dict which maps element to index, so the result dict is <code>{'aa': 0, 'bb': 1, 'cc': 2, 'dd': 3, ...}</code>. Here comes my code:</p> <pre><code>cnt = 0 mp = {} for name in name_list: mp[name] = cnt cnt += 1 return mp </code></pre> <p>It seems my code is not concise and effective, so how to improve it?</p>
<p>The shortest is to use <a href="https://docs.python.org/2/library/functions.html#enumerate"><code>enumerate</code></a> and a dict comprehension, I guess:</p> <pre><code>mp = {element: index for index, element in enumerate(name_list)} </code></pre>
Untar subfolders from a folder in linux <p>I have a directory, <code>/Landsat_Data/</code> which contains subdirectories (<code>Landsat_Data/Site1</code>, <code>Landsat_Data/Site2</code>, etc.). Each subdirectory contains <code>.tar.gz</code> files (e.g. <code>/Landsat_Data/Site2/LE70930862008092-SC20160107074735.tar.gz</code>, etc.) and each <code>.tar.gz</code> file contains tif or xml files like thisL</p> <pre><code>-rw-r--r-- espa/ie 29952 2016-01-07 14:57 LT50930861991021ASA00_sr_snow_qa.tif </code></pre> <p>What I want to do is to untar each tar file into its own sub-subdirectory (e.g. <code>Landsat_Data/Site2/LE70930862008092-SC20160107074735/</code>).</p> <p>So far, I am using this command line while being the Landsat_Data directories: </p> <pre><code>find . -type f -name "*.tar.gz" -execdir tar -xvzf {} \; </code></pre> <p>However, this command extracts all the tif and xml files into each subdirectory (e.g. <code>Landsat_Data/Site2</code>) while I just want to untar the <code>LE70930862008092-SC20160107074735.tar.gz</code> to have a sub-sub-directory called <code>LE70930862008092-SC20160107074735</code> which contains all the tif and xml files. Any idea how I can achieve what I want?</p>
<p>You might parse the filenames and cd into the directories before running <code>tar</code>. You could place a simple shell script into <code>/folder</code> like this one:</p> <pre><code>~/folder$ cat extract-in-dir.sh #!/bin/bash DIRECTORY="${1%/*}" TARFILE="${1##*/}" cd $DIRECTORY tar -xf $TARFILE </code></pre> <p>Then <code>chmod +x ./extract-in-dir.sh</code> and run it like this:</p> <p><code>find . -type f -name \*tar -exec ./extract-in-dir.sh {} \;</code></p>
pandas table subsets giving invalid type comparison error <p>I am using pandas and want to select subsets of data and apply it to other columns. e.g.</p> <ul> <li>if there is data in column A; &amp; </li> <li>if there is NO data in column B;</li> <li>then, apply the data in column A to column D</li> </ul> <p>I have this working fine for now using <code>.isnull()</code> and <code>.notnull()</code>. e.g. </p> <pre><code>df = pd.DataFrame({'A' : pd.Series(np.random.randn(4)), 'B' : pd.Series(np.nan), 'C' : pd.Series(['yes','yes','no','maybe'])}) df['D']='' df Out[44]: A B C D 0 0.516752 NaN yes 1 -0.513194 NaN yes 2 0.861617 NaN no 3 -0.026287 NaN maybe # Now try the first conditional expression df['D'][df['A'].notnull() &amp; df['B'].isnull()] \ = df['A'][df['A'].notnull() &amp; df['B'].isnull()] df Out[46]: A B C D 0 0.516752 NaN yes 0.516752 1 -0.513194 NaN yes -0.513194 2 0.861617 NaN no 0.861617 3 -0.026287 NaN maybe -0.0262874 </code></pre> <p>When one adds a third condition, to also check whether data in column C matches a particular string, we get the error:</p> <pre><code>df['D'][df['A'].notnull() &amp; df['B'].isnull() &amp; df['C']=='yes'] \ = df['A'][df['A'].notnull() &amp; df['B'].isnull() &amp; df['C']=='yes'] File "C:\Anaconda2\Lib\site-packages\pandas\core\ops.py", line 763, in wrapper res = na_op(values, other) File "C:\Anaconda2\Lib\site-packages\pandas\core\ops.py", line 718, in na_op raise TypeError("invalid type comparison") TypeError: invalid type comparison </code></pre> <p>I have read that this occurs due to the different datatypes. And I can get it working if I change all the strings in column C for integers or booleans. We also know that string on its own would work, e.g. <code>df['A'][df['B']=='yes']</code> gives a boolean list.</p> <p>So any ideas how/why this is not working when combining these datatypes in this conditional expression? What are the more pythonic ways to do what appears to be quite long-winded?</p> <p>Thanks</p>
<p>I think you need add parentheses <code>()</code> to conditions, also better is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> for selecting column with boolean mask which can be assigned to variable <code>mask</code>:</p> <pre><code>mask = (df['A'].notnull()) &amp; (df['B'].isnull()) &amp; (df['C']=='yes') print (mask) 0 True 1 True 2 False 3 False dtype: bool df.ix[mask, 'D'] = df.ix[mask, 'A'] print (df) A B C D 0 -0.681771 NaN yes -0.681771 1 -0.871787 NaN yes -0.871787 2 -0.805301 NaN no 3 1.264103 NaN maybe </code></pre>
Excluding the first 3 characters of a string using regex <p>Given any string in <strong>bash</strong>, e.g flaccid, I want to match all characters in the string but the first 3 (in this case I want to exclude "fla" and match only "ccid"). The regex also needs to work in <strong>sed</strong>.</p> <p>I have tried positive look behind and the following regex expressions (as well as various other unsuccessful ones):</p> <pre><code>^.{3}+([a-z,A-Z]+) sed -r 's/(?&lt;=^....)(.[A-Z]*)/,/g' </code></pre> <p>Google hasn't been very helpful as it only produce results like "get first 3 characters .." </p> <p>Thanks in advance!</p>
<p>If you want to get <em>all characters but the first 3</em> from a string, you can use <code>cut</code>:</p> <pre><code>str="flaccid" cut -c 4- &lt;&lt;&lt; "$str" </code></pre> <p>or bash variable subsitution:</p> <pre><code>str="flaccid" echo "${str:3}" </code></pre> <p>That will strip the first 3 characters out of your string. </p>
Relaunching PowerShell script as admin user <p>I have a quite a few computer systems which we need to deploy software. I've been using a simple method for detecting if a user is a local admin, then detecting if they have admin rights. If needed, the script relaunches with elevated privileges. If the user is not a local admin, the script relaunches using a different credentials (local admin). The script works great on systems which have a later version of PowerShell such as Windows 8 and Windows 10.</p> <p>The problem is when the user is not an admin and the script is running on Windows 7. The script uses <code>$PSScriptPath</code> to relaunch the script. I don't think this works in earlier versions of PowerShell. So I tried setting <code>$PSScriptRoot</code> myself if the Major PowerShell version is &lt; 3. The problem is then the script gets stuck in a loop of some sort where it just constantly opens and closes windows and then I have to kill it... If I don't define <code>$PSScriptRoot</code> I get the error</p> <blockquote> <p>Cannot bind argument to parameter 'Path' because it is null</p> </blockquote> <p>I assume this is because <code>$PSScriptRoot</code> isn't defined in PowerShell 2.0.</p> <p>Here's an example of what I'm trying to do:</p> <pre><code>#Check if PowerShell version is greater than 2. If not, set $PSSriptRoot. if ($PSVersionTable.PSVersion.Major -lt 3) { $PSScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition } #Check if the user is a local admin. If they are, set $LocalAdmin to $True. $LocalAdmin = $false if ((net localgroup administrators) -match ([System.Environment]::UserDomainName + "\\" + [System.Environment]::Username)) { $LocalAdmin = $true } if ($LocalAdmin) { #Check if the local admin needs to run the script as administrator if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { $arguments = "&amp; '" + $MyInvocation.MyCommand.Definition + "'" Start-Process powershell -Verb runas -ArgumentList $arguments break } } else { #Not a local admin. Relaunch script as admin user. Start-Process -Credential $credential (Join-Path $PSHome powershell.exe) -ArgumentList (@("-File", (Join-Path $PSScriptRoot $MyInvocation.MyCommand)) + $args) exit } </code></pre>
<p>Don't re-define <a href="https://technet.microsoft.com/en-us/library/hh847768.aspx" rel="nofollow">automatic variables</a>. Nothing good will come of it.</p> <p>Besides, why do you want to anyway? The only thing you use <code>$PSScriptRoot</code> for is to reconstruct the script path you already have. Just assign that path to a variable and use that in your script.</p> <pre><code>$script = $MyInvocation.MyCommand.Definition $ps = Join-Path $PSHome 'powershell.exe' $isLocalAdmin = [bool]((net localgroup administrators) -match "$env:USERDOMAIN\\$env:USERNAME") if ($isLocalAdmin) { if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]'Administrator')) { Start-Process $ps -Verb runas -ArgumentList "&amp; '$script'" exit } } else { Start-Process $ps -ArgumentList (@('-File', $script) + $args) -Credential $credential exit } </code></pre>
unable to iterate through for loop in windows batch script <p>Goal: Given string "CAR080 CAR085 CAR087" I need to iterate through all three cars and perform copying of files from the carname folder.</p> <p>Need to copy files from individual car folders by looping through it. Code:</p> <pre><code> @echo off set basesource=xyz\ set year=%date:~10,4% set destination=C:\ARWISdata\year%year% set tempDir=DATAARWIS\DATARP_%year% set s= CAR080 CAR085 CAR087 set t=%s% echo t:%t% :loop for /f "tokens=1*" %%a in ("%t%") do ( set temp1=%%a set SLASH=\ echo basesource:%basesource% echo temp1:%temp1% set source=%basesource%%temp1%%SLASH%%tempDir% echo source:%source% IF EXIST %source% (echo source exists) echo destination: %destination% IF EXIST %destination% (echo destination exists) ELSE (mkdir C:\ARWISdata\year%year%) for /f %%a in ('xcopy /S /E /Y /D "%source%" "%destination%" ') do ( echo.Copying file '%%a' ) set t=%%b ) if defined t goto :loop but it is not giving me exact solution. As it needs to take first CAR080 and perform copy operation then in next cycle it should take CAR085 and perform copying and then finally CAR087. Need the code urgently. </code></pre>
<p>Just simplify. This is equivalent to your code but without variables being set inside the <code>for</code> block, so you don't need delayed expansion (read <a href="http://stackoverflow.com/a/30177832/2861476">here</a>) to retrieve the value from the changed variables</p> <pre class="lang-dos prettyprint-override"><code>@echo off setlocal enableextensions disabledelayedexpansion set "baseSource=xyz" set "year=%date:~10,4%" set "tempDir=DATAARWIS\DATARP_%year%" set "destination=C:\ARWISdata\year%year%" 2&gt;nul mkdir "%destination%" for %%a in (CAR080 CAR085 CAR087) do ( xcopy "%baseSource%\%%a\%tempDir%" "%destination%" ) </code></pre>
How to assign value to cell in excel VBA after clearing validation <p>So my vba function should assign different values to a cell based on a boolean input. True part works perfectly, however I'm getting stuck with the False statement. The True part assigns a drop down list to the cell, and the False part should erase it, and set its value to text "N/A". As soon as I'm trying to change the value of the cell (or any cells actually, with range("..").value command, the code faces an error.</p> <p>Is there an other way around? Thanks in advance!</p> <pre><code>Function sema_list(rng As Range, sema As Boolean) If sema = True Then With rng.Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ Operator:=xlBetween, Formula1:="=arrangement" .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = True End With End If If sema = False Then rng.Validation.Delete rng.Value = "some text" End If sema_list = "" End Function </code></pre>
<p>I guess you have to pass some range before assigning any value. For eg:</p> <pre><code>Range("A1:A10") = "some text" </code></pre> <p>or maybe something like this:</p> <pre><code>Dim example As Range Set example = Range("A1:A10") example.Value = 8 </code></pre>
Read regexes from file and avoid or undo escaping <p>I want to read regular expressions from a file, where each line contains a regex:</p> <pre><code>lorem.* dolor\S* </code></pre> <p>The following code is supposed to read each and append it to a list of regex strings:</p> <pre><code>vocabulary=[] with open(path, "r") as vocabularyFile: for term in vocabularyFile: term = term.rstrip() vocabulary.append(term) </code></pre> <p>This code seems to escape the <code>\</code> special character in the file as <code>\\</code>. How can I either avoid escaping or unescape the string so that it can be worked with as if I wrote this?</p> <pre><code>regex = r"dolor\S*" </code></pre>
<p>You are getting confused by <em>echoing the value</em>. The Python interpreter echoes values by printing the <code>repr()</code> function result, and this makes sure to escape any meta characters:</p> <pre><code>&gt;&gt;&gt; regex = r"dolor\S*" &gt;&gt;&gt; regex 'dolor\\S*' </code></pre> <p><code>regex</code> is still an 8 character string, not 9, and the single character at index 5 is a single backslash:</p> <pre><code>&gt;&gt;&gt; regex[4] 'r' &gt;&gt;&gt; regex[5] '\\' &gt;&gt;&gt; regex[6] 'S' </code></pre> <p>Printing the string writes out all characters verbatim, so no escaping takes place:</p> <pre><code>&gt;&gt;&gt; print(regex) dolor\S* </code></pre> <p>The same process is applied to the contents of containers, like a <code>list</code> or a <code>dict</code>:</p> <pre><code>&gt;&gt;&gt; container = [regex, 'foo\nbar'] &gt;&gt;&gt; print(container) ['dolor\\S*', 'foo\nbar'] </code></pre> <p>Note that I didn't echo there, I printed. <code>str(list_object)</code> produces the same output as <code>repr(list_object)</code> here.</p> <p>If you were to print individual elements from the list, you get the same unescaped result again:</p> <pre><code>&gt;&gt;&gt; print(container[0]) dolor\S* &gt;&gt;&gt; print(container[1]) foo bar </code></pre> <p>Note how the <code>\n</code> in the second element was written out as a newline now. It is for <em>that reason</em> that containers use <code>repr()</code> for contents; to make otherwise hard-to-detect or non-printable data visible.</p> <p>In other words, your strings do <em>not</em> contain escaped strings here.</p>
Save JSON Decode to MySQL , PHP <p>Good Day Please can you assist I'm trying to update a mysql table with a JSON POST. The JSON output into a textfile fine but when I try and save it to the MySQL table then supplies an error:</p> <blockquote> <p>Undefined index: ptp.create</p> </blockquote> <p>The JSON Outputs the data as:</p> <pre><code>{"ptp.create":["629","630"]} $jsonString = file_get_contents("php://input"); $myFile = "NewFile.txt"; file_put_contents($myFile,$jsonString); $data = json_decode($jsonString, true); foreach ($data as $row){ $PTP = $row['ptp.create']; $query_rsTable1 = "INSERT INTO test SET id = '$PTP'"; $rsTable1 = mysql_query($query_rsTable1, $int) or die(mysql_error()); } </code></pre> <p>I'm not very 100% confident in JSON yet, if you could please assist. </p>
<p>Your <code>for</code> loop has already taken care of the <code>ptp.create</code> for you.</p> <pre><code>foreach ($data as $ptp){ echo $ptp; // Will be 629, then 630 } </code></pre> <p>When you actually insert into your database, use prepared/parameterized queries with PDO or similar.</p>
Multiple find and replace in MS Word from a list in MS Excel <p>Hi I really hope you can help me as I've been trying to do this for a while with not a lot of luck. </p> <p>I have a list in Excel, say, file 1 (say, A1 - B10, 2 columns of words - the words in column A are the ones to be replaced by the ones in column B).</p> <p>I have a document in word, say, file 2, which I want to run the words in the excel file so that every appearance of any words which are in column A of the excel file is replaced by the corresponding words in column B.</p> <p>I would really appreciate any help you could give me, thank you so much.</p>
<p>If I understood you right, you want to replace Words in your Word Document with Words listed in your Excel File. If so, this macro should do the trick(Macro for MS Word):</p> <pre><code>Function findAndReplace() Dim xlApp As Object Dim xlWB As Object Dim xlWS As Object Dim i As Integer, j As Integer Dim lastRow As Integer 'Set Objects Set xlApp = CreateObject("Excel.Application") Set xlWB = xlApp.Workbooks.Open("PATH TO EXCEL FILE") 'Replace String with path to Excel File Set xlWS = xlWB.Worksheets("Name of Worksheet") 'Replace String with your Worksheet Name 'get last row of excel file lastRow = xlWS.UsedRange.SpecialCells(xlCellTypeLastCell).Row 'loop through all words in Word Document For i = 1 To ThisDocument.Words.Count - 1 Step 1 'Loop through cells in Excel File For j = 1 To lastRow Step 1 'Replace Word value in Column B of Excel File ThisDocument.Words(i) = Replace(ThisDocument.Words(i), xlWS.Cells(j, 1).Value, xlWS.Cells(j, 2).Value) Next j Next i 'Close Excel and Cleanup Set xlWS = Nothing xlWB.Close True Set xlWB = Nothing xlApp.Quit Set xlApp = Nothing </code></pre> <p>End Function</p> <p>If I understood you wrong, please give us more detail on what you are trying to do.</p>
Matlab random sampling <p>I am trying to exercise myself in Matlab. I am trying to select randomly two lines from a file named data.dat. </p> <p>My data.dat file looks like this:</p> <pre><code>12 4 6.1 7 14 4 8.4 62 7 56.1 75 98 9.7 54 12 35 2 4 8 7.8 </code></pre> <p>To select 2 lines randomly from the data.dat here is how I am proceeding:</p> <pre><code>close all; clear all; %----------------------% % Choose random lines %----------------------% M = load('data.dat'); N=2; %number_of_lines file_number = 2; %save each two lines in new file: selection_1, selection_2 </code></pre> <p>Now I am saving the two selected lines in new files sequentially. </p> <pre><code>for k = 1:file_number i = randi(length(M),N); B=M(i,:) filename=['samples_',int2str(k),'_mc.dat'] save (filename, 'B', '-ascii') clear B; end </code></pre> <p>I don't know why but I have more than 2 lines in each new files. Could you please explain me where did I made a mistake.</p>
<p>I think you are making a mistaking when you generate the random numbers, as indicated by GameOfThrows.</p> <pre><code>i = randi(length(M),N); % gives you a matrix NxN of numbers i = randi(length(M),[N,1]); % gives you a column of N numbers </code></pre>
GIF from external resource in page is not animating in apache wicket web application <p>I am using external images in my webaplication, everything wass fine until I wanted to add animated gif there, the gif loads, but it doesn't animate.</p> <p>Java code:</p> <pre><code> File sourceimage = new File("loading_img.gif"); try { final BufferedDynamicImageResource r = new BufferedDynamicImageResource("GIF"); r.setImage(ImageIO.read(sourceimage)); add(new Image("gif", r)); } catch (Exception e) { e.printStackTrace(); } </code></pre> <p>HTML:</p> <pre><code> &lt;img wicket:id="gif"/&gt; </code></pre> <p>EDIT:</p> <p>Tried martin-g suggestion, gif still doesn't animate</p> <pre><code> try { final BufferedDynamicImageResource r = new BufferedDynamicImageResource("GIF"){ @Override protected void setResponseHeaders(AbstractResource.ResourceResponse data, IResource.Attributes attributes){ super.setResponseHeaders(data, attributes); data.setContentType("image/gif"); } }; r.setImage(ImageIO.read(sourceimage)); add(new Image("gif", r)); } catch (Exception e) { e.printStackTrace(); } </code></pre>
<p>The problem is that the content type is not automatically set. You will need to override org.apache.wicket.request.resource.AbstractResource#setResponseHeaders() and set with via <code>resourceResponse.setContentType(String)</code>.</p> <p>Maybe this should be done automatically by Wicket in org.apache.wicket.request.resource.DynamicImageResource, since it knows the format ("png", or "gif" as in your case). Please file a ticket in Wicket's JIRA for this improvement! Thanks!</p>
deleting from two tables in single script in sql <p>I have three tables <code>xx_1 , xx_2, xx_3</code> such that :</p> <p>xx_1 </p> <pre><code>id obj_version_num location 1 x ubudu 2 x bali 3 x india </code></pre> <p>xx_2 </p> <pre><code>id name grade 1 abc band 1 2 xyz band 2 3 gdgd band 3 </code></pre> <p>xx_3 has :</p> <pre><code> Name details col1 p_id abc A HDHD 10 xyz B HDHD 20 gdgd C HDHD 30 smith D HDHD 40 </code></pre> <p>I want to delete data from xx_1 and xx_2 if the name is smith in xx_3 Currently i am doing :</p> <pre><code>delete from xx_1 where id in (select distinct id from xx_2 t ,xx_3 k where t.name=k.name and k.name ='Smith') and then delete from xx_2 where name ='Smith' </code></pre> <p>Is there anyway i can delete data from both these table together ? without creating two separate scripts ? </p>
<p>There is no way to delete from many tables with a single statement, but the better question is why do you need to delete from all tables at the same time? It sounds to me like you don't fully understand how transactions work in Oracle.</p> <p>Lets say you login and delete a row from table 1, but do not commit. As far as all other sessions are concerned, that row has not been deleted. If you open another connection and query for the row, it will still be there.</p> <p>Then you delete from tables 2, 3 and then 4 in turn. You still have not committed the transaction, so all other sessions on the database can still see the deleted rows.</p> <p>Then you commit.</p> <p>All at the same time, the other sessions will no longer see the rows you deleted from the 4 tables, even though you did the deletes in 4 separate statements.</p> <p>EDIT after edit in question:</p> <p>You can define the foreign keys on the 3 child tables to "<code>ON DELETE CASCADE</code>". Then when you delete from the parent table, all associated rows from the 3 child tables are also deleted. </p>
t.time saving field as a string in ActiveRecord <p>I have a table with a field called <code>time_start</code>. Example: </p> <pre><code>t.time :time_start </code></pre> <p>When I try to save the attribute, it saves it as a Hash-String. Example: </p> <pre><code>params{ "time_start(1i)"=&gt;"2016", "time_start(2i)"=&gt;"10", "time_start(3i)"=&gt;"12", "time_start(4i)"=&gt;"23", "time_start(5i)"=&gt;"59", } =&gt; "{1=&gt;2016, 2=&gt;10, 3=&gt;12, 4=&gt;23, 5=&gt;59}" </code></pre> <p>I cannot figure out why the attribute is saving a string instead of parsing into a Time obj. I have even tried a <code>rake db:rollback VERSION=123456546</code> to the migration just before it, but it still saves the value as a string after the <code>rake db:migrate</code>. I am not allowed to drop the table.</p>
<p>Looking back through the commits, a Junior dev originally assigned the <code>time_start</code> field as a <code>string</code> data-type in table <code>B</code>. The solution was to grab the version number of the previous migration (table <code>A</code>), and run <code>rake db:migrate VERSION=213412341234</code>, then <code>rake db:migrate</code>. It is now saving correctly. </p>
HTML - How do I insert a <span></span> tag into each line of a <pre></pre> block without hard coding? <p>I was just trying to add line numbers at the beginning of source code using CSS. I realized the effect I wanted, as follows:</p> <p><a href="https://i.stack.imgur.com/A0P12.png" rel="nofollow"><img src="https://i.stack.imgur.com/A0P12.png" alt="Effect implemented"></a></p> <p>However, the HTML code required continual use of <code>&lt;span&gt;...&lt;/span&gt;</code> tags:</p> <pre><code>&lt;pre class="code"&gt; &lt;span&gt;var links = document.getElementsByClassName("link");&lt;/span&gt; &lt;span&gt;for(var i = 0; i &amp;lt; links.length; i++){&lt;/span&gt; &lt;span&gt; links[i].onclick=function(){&lt;/span&gt; &lt;span&gt; alert(i+1);&lt;/span&gt; &lt;span&gt; };&lt;/span&gt; &lt;span&gt;}&lt;/span&gt; &lt;/pre&gt; </code></pre> <p>With the <code>span</code> tags positioned at home/end of lines I can let the line numbers show as expected. But I think there must be another better solution to prevent me adding all these <code>span</code> tags hard-coded, maybe using Javascript, or jQuery I don't mind but don't know how. Please help.</p> <p>NOTE:<br> My problem is not how to display line numbers when the <code>&lt;span&gt;</code> tags are already there. Instead, I wanted to know if the origin HTML code contains NO <code>&lt;span&gt;</code> tags, how can I automatically add them into the suitable places and so I can apply the CSS styles.</p>
<p>This can be achieved by using CSS counters</p> <p>This does not require any JavaScript (or jQuery) which means no need for each libraries or scripts and was introduced way back in CSS 2.1 so has great browser support across the board.</p> <p>You can read up more in the <a class='doc-link' href="http://stackoverflow.com/documentation/css/2575/counters#t=201610121316086391368">SO Docs</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>pre { background: #eee; counter-reset: section; /* Reset the counter to 0 for each new pre */ } pre span:before { counter-increment: section; /* Increment the section counter*/ content: counter(section); /* Display the counter */ padding: 0 5px; border-right: 1px solid #777; margin-right: 5px; color: #777 }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;pre class="code"&gt; &lt;span&gt;var links = document.getElementsByClassName("link");&lt;/span&gt; &lt;span&gt;for(var i = 0; i &amp;lt; links.length; i++){&lt;/span&gt; &lt;span&gt; links[i].onclick=function(){&lt;/span&gt; &lt;span&gt; alert(i+1);&lt;/span&gt; &lt;span&gt; };&lt;/span&gt; &lt;span&gt;}&lt;/span&gt; &lt;/pre&gt; &lt;pre class="code"&gt; &lt;span&gt;var links = document.getElementsByClassName("link");&lt;/span&gt; &lt;span&gt;for(var i = 0; i &amp;lt; links.length; i++){&lt;/span&gt; &lt;span&gt; links[i].onclick=function(){&lt;/span&gt; &lt;span&gt; alert(i+1);&lt;/span&gt; &lt;span&gt; };&lt;/span&gt; &lt;span&gt;}&lt;/span&gt; &lt;/pre&gt;</code></pre> </div> </div> </p>
SML Operator and operand don't agree in foldr <p>I'm working on an assignment where I have to write a function to get the length of a list. This is a trivial task, but I've come across something that I don't understand.</p> <p>My simple code</p> <pre><code>val len = foldr (fn(_, y) =&gt; y + 1) 0 </code></pre> <p>produces this warning</p> <blockquote> <p>Warning: type vars not generalized because of value restriction are instantiated to dummy types (X1,X2,...)</p> </blockquote> <p>and when I try to run it in the REPL, I get this:</p> <pre><code>len [1, 2, 3, 4]; stdIn:18.1-18.17 Error: operator and operand don't agree [overload conflict] operator domain: ?.X1 list operand: [int ty] list in expression: len (1 :: 2 :: 3 :: &lt;exp&gt; :: &lt;exp&gt;) </code></pre> <p>I don't understand why this doesn't work. I do know some functional programming principles, and this should work, since its very simple partial application.</p> <p>Of course I can make it work without partial application, like this</p> <pre><code>fun len xs = foldr (fn(_, y) =&gt; y + 1) 0 xs </code></pre> <p>but I would like to understand why the first version doesn't work.</p>
<p>This is an instance of the <a href="http://mlton.org/ValueRestriction" rel="nofollow">value restriction</a> rule application:</p> <blockquote> <p>In short, the value restriction says that generalization can only occur if the right-hand side of an expression is syntactically a value. </p> </blockquote> <p>Syntactically,</p> <pre><code>foldr (fn(_, y) =&gt; y + 1) 0 </code></pre> <p>is <em>not</em> a value, it's a function application, that's why it hasn't been assigned a <em>polymorphic</em> type. It has been instantiated with a dummy type, which has a very limited use, e.g. this works:</p> <pre><code>len [] </code></pre> <p>but in most cases <code>len</code> defined as <code>val</code> is useless.</p> <p>This restriction exists to guarantee type safety in the presence of variable assignment (via references). More details can be found in the linked page.</p>
Echo option value with selected <p>Im tryin to fix when i press my search button. That the selected search from my option field remains selected. But at the moment it automaticly picks the first field of the options in my form.</p> <p>First one is hardcoded and it works.</p> <pre><code>&lt;option value="HS" &lt;?= ($nickval == 'HS' ? 'selected="selected' : '')?&gt;&gt;Homer Simpsons&lt;/option&gt; </code></pre> <p>But then i wanted to echo out option value from database so its not hardcoded.</p> <pre><code>&lt;?php while(db2_fetch_row($queryexe)) { echo "&lt;option value='$pin'&gt;$fullname&lt;/option&gt;"; } ?&gt; </code></pre> <p>And now when i want to add if its selected i tried to solve it like this.</p> <pre><code>echo "&lt;option value='$pin'($nickval == '$pin' ? 'selected='selected'' : '')&gt;$fullname &lt;/option&gt;"; </code></pre> <p>This is how i get my pin</p> <pre><code> $pin = db2_result($queryexe, 'P510PIN'); </code></pre> <p>This is how i get my $nickval</p> <pre><code> $nickval = $_GET["int"]; </code></pre> <p>Any suggestions what im doin wrong? Sorry if im unclear but i've tried my best</p>
<p>Aside from quoting errors indicated in the syntax highlighting...</p> <p>You're trying to execute PHP code inside of a string:</p> <pre><code>echo "&lt;option value='$pin'($nickval == '$pin' ? 'selected='selected'' : '')&gt;$fullname &lt;/option&gt;"; </code></pre> <p>Variable interpolation is one thing, but code inside of a string isn't going to automatically execute. It's just a string being echoed to the page. (Check the page source and see what's actually being emitted to the browser.)</p> <p>Separate the strings from the code which builds the strings:</p> <pre><code>echo "&lt;option value='$pin' " . ($nickval == $pin ? "selected='selected'" : "") . "&gt;$fullname &lt;/option&gt;"; </code></pre>
Print filename only with Robocopy <p>I'm copying files with Robocopy but path+filename is too long and the output gets too crowded. I would like to display filename only (without path).</p> <p>My command is:</p> <pre><code>ROBOCOPY /NDL /NFL /NJH /NJS /nc /ns %path% %local% %filename% </code></pre> <p>and outputs:</p> <pre><code>100% \\storage\releases\prog\ver\file.exe </code></pre> <p>I would like to output:</p> <pre><code>100% file.exe </code></pre> <p>I've seen the <code>/FP</code> flag but I actually want the opposite of that.</p> <pre><code>/FP : Include Full Pathname of files in the output. </code></pre>
<p>The indicated command does not return the indicated output. You are explicitly using <code>/nfl</code> that will remove the file list.</p> <p>But, without <code>/nfl</code> but keeping <code>/ndl</code> we get the indicated behaviour: If we don't include the directory list, file names will include the full path. </p> <p>To get the required behaviour, remove the <code>/ndl</code>. As this will include in the output the folder being processed, if you dont want it, filter the <code>robocopy</code> output to discard any line containing a backslash</p> <pre class="lang-dos prettyprint-override"><code>robocopy %path% %local% %filename% /NJH /NJS /nc /ns | find /v "\" </code></pre>
How to get cursor position in an image with Matlab <p>I need to get the cursor position after a click on the image to obtain the corresponding pixel coordinates. This is what I've done so far, which works as long as I click on the empty part of the figure (if I click on the image, the callback is not triggered).</p> <pre><code>image(my_image); set(gca, 'ButtonDownFcn', @click); function click(o, event) pt = get(o, 'CurrentPoint') end </code></pre> <p>So afterward, I tried this one :</p> <pre><code>image(my_image, 'ButtonDownFcn', @click); function click(o, event) pt = get(o, 'CurrentPoint') end </code></pre> <p>But then, it tells me that the image class does not contain any field named 'CurrentPoint'. I suppose that I need to retrieve some kind of axes from the image, but I don't know how to do that.</p>
<p>I've had to solve a similar problem before.</p> <p>If you add an empty callback like the following the gui will track the cursor position</p> <pre><code>function figure1_WindowButtonMotionFcn(~, ~, ~) </code></pre> <p>Then the figure1 handle should have a property <code>currentPoint</code> that will describe the position of the mouse. If you write a click event function that has access to the figure1 handle, something like this:</p> <pre><code>image(my_image, 'ButtonwDownFcn', ... @(hObject,eventdata)myGui('click',hObject,eventdata,guidata(hObject)) </code></pre> <p>include the following line in it to access the mouse position</p> <pre><code>mouseLocation = get(handles.figure1, 'currentPoint'); </code></pre> <p>Then you'll have to translate the mouse position to pixel position using the position of the axes inside the figure.</p>
Convert json to Object List <p>I have the following String: </p> <pre><code>String json = "[{\"id\": \"0\", \"ip\": \"123\", \"mac\": \"456\"}, {\"id\": \"1\", \"ip\": \"111\", \"mac\": \"222\"}]"; </code></pre> <p>And a SlaveEntity Entity that has:</p> <pre><code>public class SlaveEntity extends BaseEntity { private String ip; private String macAddress; private String status; @OneToMany(mappedBy="slave", targetEntity = PositionEntity.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL) private List&lt;PositionEntity&gt; positions; } </code></pre> <p>I am writing a method that takes the json and returns a List of SlaveEntity: </p> <pre><code>public static List&lt;SlaveEntity&gt; JsonToSlaveEntity(String json) { ObjectMapper objectMapper = new ObjectMapper(); List&lt;SlaveEntity&gt; obj = new ArrayList&lt;SlaveEntity&gt;(); try { obj = objectMapper.readValue(json, List.class); } catch (IOException e) { e.printStackTrace(); } return obj; } </code></pre> <p>The problem is that the obj List results like this: </p> <p><a href="https://i.stack.imgur.com/qOb1Z.png" rel="nofollow"><img src="https://i.stack.imgur.com/qOb1Z.png" alt="enter image description here"></a></p> <p>But what I need the obj List to be is like this: </p> <p><a href="https://i.stack.imgur.com/cx2xv.png" rel="nofollow"><img src="https://i.stack.imgur.com/cx2xv.png" alt="enter image description here"></a></p> <p>So how can I get the needed list?</p>
<p>You can convert the result to an object list, or you can pass in a type parameter rather than the <code>List</code> class.</p> <pre><code>String jsonString = "[{\"id\": \"0\", \"ip\": \"123\", \"mac\": \"456\"}, {\"id\": \"1\", \"ip\": \"111\", \"mac\": \"222\"}]"; </code></pre> <h3>With <code>Object</code></h3> <pre><code>List&lt;Object&gt; items = objectMapper.readValue( jsonString, objectMapper.getTypeFactory().constructParametricType(List.class, Object.class) ); </code></pre> <h3>With <code>SlaveEntity</code></h3> <pre><code>List&lt;SlaveEntity&gt; items = objectMapper.readValue( jsonString, objectMapper.getTypeFactory().constructCollectionType(List.class, SlaveEntity.class) ); </code></pre> <hr> <h1>Update</h1> <p>This is what I have come up with, and it works.</p> <h3>EntityTest</h3> <pre><code>import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; public class EntityTest { public static void main(String[] args) { String json = "[{\"id\": \"0\", \"ip\": \"123\", \"mac\": \"456\"}, {\"id\": \"1\", \"ip\": \"111\", \"mac\": \"222\"}]"; for (SlaveEntity entity : jsonToSlaveEntity(json)) { System.out.println(entity); } } public static List&lt;SlaveEntity&gt; jsonToSlaveEntity(String json) { ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.readValue( json, objectMapper.getTypeFactory().constructCollectionType(List.class, SlaveEntity.class) ); } catch (IOException e) { e.printStackTrace(); } return new ArrayList&lt;SlaveEntity&gt;(); } } </code></pre> <h3>BaseEntity</h3> <pre><code>public class BaseEntity { private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } } </code></pre> <h3>SlaveEntity</h3> <pre><code>import java.util.List; import javax.persistence.CascadeType; import javax.persistence.FetchType; import javax.persistence.OneToMany; import com.fasterxml.jackson.annotation.JsonProperty; public class SlaveEntity extends BaseEntity { private String ip; @JsonProperty("mac") private String macAddress; private String status; @OneToMany(mappedBy = "slave", targetEntity = PositionEntity.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL) private List&lt;PositionEntity&gt; positions; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List&lt;PositionEntity&gt; getPositions() { return positions; } public void setPositions(List&lt;PositionEntity&gt; positions) { this.positions = positions; } @Override public String toString() { return String.format( "SlaveEntity [id=%d, ip=%s, mac=%s, status=%s, positions=%s]", getId(), ip, macAddress, status, positions); } } </code></pre> <h3>PositionEntity</h3> <pre><code>public class PositionEntity { // ? } </code></pre> <h3>Result</h3> <pre><code>SlaveEntity [id=0, ip=123, mac=456, status=null, positions=null] SlaveEntity [id=1, ip=111, mac=222, status=null, positions=null] </code></pre>
Changing all links on page with js <p>I want to remove "/index.php" in all links on page</p> <p>Example:</p> <pre class="lang-none prettyprint-override"><code>http://example.com/?hostname=sad2.cherobr.ru&amp;path=/index.php/o-nas </code></pre> <p>change to:</p> <pre class="lang-none prettyprint-override"><code>http://example.com/?hostname=sad2.cherobr.ru&amp;path=/o-nas </code></pre>
<p>with plain js</p> <pre><code>var allAnchors = document.querySelectorAll("a"); Array.prototype.slice.call( allAnchors ).forEach( function( el ){ var href = el.getAttribute( "href" ); el.setAttribute( "href", href.replace( "/index.php", "" ) ); }); </code></pre>
Java. The same objects with different hashes <p>I have two objects from database (in database it is same object), but they have different hashes:</p> <pre><code>GroupType groupType = groupTypeDao.findById(3); GroupType groupType1 = groupTypeDao.findById(3); System.out.println(groupType); System.out.println(groupType1); </code></pre> <p>I get this output:</p> <pre><code>GroupType@6040 GroupType@6041 </code></pre> <p>Why is that? Technology stack: Spring, JavaFX, Hibernate.</p> <p>I have another project with Spring and Hibernate. Configuration files are identical in the two projects. Hibernate version is identical also. But in another project this produce same hashcodes.</p>
<p>What you've printed are object references. They are indeed different if you created each reference by calling new.</p> <p>You need to override equals, hashCode, and toString according to "Effective Java" to get the behavior you want.</p>
Create 4D upper diagonal array from 3D <p>Let's say that I have a <code>(x, y, z)</code> sized matrix. Now, I wish to create a new matrix of dimension <code>(x, y, i, i)</code>, where the <code>(i, i)</code> matrix is upper diagonal and constructed from the values on the <code>z</code>-dimension. Is there some easy way of doing this in <code>numpy</code> without using more than 1 for-loop (looping over x)? Thanks.</p> <p><strong>EDIT</strong></p> <pre><code>original = np.array([ [ [0, 1, 3], [4, 5, 6] ], [ [7, 8, 9], [3, 2, 1] ], ]) new = np.array([ [ [ [0, 1], [0, 3] ], [ [4, 5], [0, 6] ] ], [ [ [7, 8], [0, 9] ], [ [3, 2], [0, 1] ] ] ]) </code></pre> <p>So, using the above we see that</p> <pre><code>original[0, 0, :] = [0 1 3] new[0, 0, :, :] = [[0 1] [0 3]] </code></pre>
<p>Here's an approach using <code>boolean-indexing</code> -</p> <pre><code>n = 2 # This would depend on a.shape[-1] out = np.zeros(a.shape[:2] + (n,n,),dtype=a.dtype) out[:,:,np.arange(n)[:,None] &lt;= np.arange(n)] = a </code></pre> <p>Sample run -</p> <pre><code>In [247]: a Out[247]: array([[[0, 1, 3], [4, 5, 6]], [[7, 8, 9], [3, 2, 1]]]) In [248]: out Out[248]: array([[[[0, 1], [0, 3]], [[4, 5], [0, 6]]], [[[7, 8], [0, 9]], [[3, 2], [0, 1]]]]) </code></pre> <p>Another approach could be suggested using <code>subscripted-indexing</code> to replace the last step -</p> <pre><code>r,c = np.triu_indices(n) out[:,:,r,c] = a </code></pre> <p><strong>Note :</strong> As stated earlier, <code>n</code> would depend on <code>a.shape[-1]</code>. Here, we had <code>a.shape[-1]</code> as <code>3</code>, so <code>n</code> was <code>2</code>. If <code>a.shape[-1]</code> were <code>6</code>, <code>n</code> would be <code>3</code> and so on. The relationship is : <code>(n*(n+1))//2 == a.shape[-1]</code>.</p>
Add on-premise nodes to GKE <p>How do I add my on-premise node to my managed cluster?</p> <p>I've tried doing "kubeadm join --token " with a default-token from the ui and the cluster endpoint as ip.</p>
<p>You can add an on-prem node to your GKE cluster if you manually configure the kubelet (basically what kubeadm makes nice and easy). </p> <p>Your cluster may not work as expected though unless you also create a VPN connection between the on-prem node and your cloud network where the rest of your nodes are running and also configure networking routes to map a node CIDR to your on-prem node. Otherwise, cross-pod networking will not work.</p> <p>In addition, features like <code>kubectl exec</code> and <code>kubectl logs</code> likely won't work for any pods running on your on-prem node. </p>
can we call python script in node js and run node js to get call? <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>python.py from pymongo import MongoClient from flask import Flask app = Flask(__name__) host = "10.0.0.10" port = 8085 @app.route('/name/&lt;string:name&gt;',methods=['GET','POST']) def GetNoteText(name): print name return "Data Received" @app.route('/', methods=['POST']) def abc(): print "Hii" return ('Welcome') users=[] @app.route('/getNames') def getName(): client = MongoClient('mongodb://localhost:27017/') db = client.bridgeUserInformationTable cursor = db.bridgeUsersInfo.find() for document in cursor: #print "Name : ",document['name'] users.append(document['name']) print document['name'] #print (users) return "&lt;html&gt;&lt;body&gt;&lt;h1&gt;"+str(users)+"&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;" if __name__ == '__main__': app.run( host=host, port=port )</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>node.j var PythonShell = require('python-shell'); PythonShell.run('pass.py', function (err) { if (err) throw err; console.log('finished'); });</code></pre> </div> </div> </p> <p>As i tried can we call python script in node js after running node js script from getting input from the android device? I am lit bit confused how it should be solved? And how both languages should communicate each other like python to node js? </p>
<p><a href="http://www.zerorpc.io/" rel="nofollow">ZERORPC</a> is a really nifty library built on top of ZeroMQ. This is probably the easiest way to make call python code from Node.</p> <p>For a really simple approach and non-robust approach, you could use a tmp file to write the python commands from Node. With an event loop running inside Python, read the tmp file for any changes and execute the commands therein. </p>
Force WPF application to maximize on Windows startup <p>I have a WPF app that installed on Windows 10 Pro via ClickOnce and uses MahApps.Metro.</p> <p>It is set to launch on Windows boot with a non-admin account that has no password. Tablet mode is enabled.</p> <p>I want the application pop up full screen to create <strong>kiosk</strong>-like experience, however the <strong>app starts minimized</strong> when launching on boot. To clarify, the WindowState is Maximized, but Windows does not show it, instead it shows the start screen. It launches fullscreen maximized when launching manually.</p> <p>Here is some code, however I guess this is more of a configuration problem than code problem:</p> <p>This is how I set the launch on boot:</p> <pre><code>RegistryKey rkApp = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); string startPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs) + @"\Publisher\AppName.appref-ms"; rkApp.SetValue("AppName", startPath); </code></pre> <p>This is MainWindow.xaml</p> <pre><code>&lt;Controls:MetroWindow x:Class="AppName.MainWindow" IgnoreTaskbarOnMaximize="True" ShowTitleBar="False" WindowStyle="None" WindowState="Maximized"&gt; ... &lt;/Controls:MetroWindow&gt; </code></pre>
<p>You can do this in the MainWindow.xaml.cs by adding a windowstate of maximized.</p> <pre><code>public MainWindow() { InitializeComponent(); this.WindowState = WindowState.Maximized; } </code></pre>
Save as zip instead tar <p>Is it possible to change it (archive as tar) to archive as zip? I am not good in php </p> <pre><code>if (ARCHIVE &amp;&amp; isset($_GET['archive'])) { $log -&gt; add_entry('Directory archived'); $outfile = Item::get_basename($subdir); if ($outfile == '' || $outfile == '.') { $outfile = 'base_dir'; } $mime = new MimeType('.tar'); header('Content-Type: ' . $mime -&gt; __toString()); header('Content-Disposition: attachment; filename="' . $outfile . '.tar"'); @set_time_limit(0); $list = new DirectoryList($dir); $tar = new Tar($list, $outfile, strlen($dir)); die(); } </code></pre>
<p>Yes, you can use the PHP <a href="http://php.net/manual/en/class.ziparchive.php" rel="nofollow">ZipArchive</a> object. </p> <p>i.e. (from source link) : </p> <pre><code>&lt;?php $files = array('image.jpeg','text.txt','music.wav'); $zipname = 'enter_any_name_for_the_zipped_file.zip'; $zip = new ZipArchive; $zip-&gt;open($zipname, ZipArchive::CREATE); foreach ($files as $file) { $zip-&gt;addFile($file); } $zip-&gt;close(); </code></pre> <p>Hope it helps.</p>
TRIGGERS need help on sql <p>How Can I remove all the numeric character and special characters from this string value '2016-05-27T12:12:12.000Z' need this solution early please guide me on this in triggers</p>
<p>If we follow your need then below one can be fullfill in <code>Oracle</code>, bt as mentioned in commnents, "What use is that date if you remove all the numeric characters"..stands valid..</p> <pre><code>select '2016-05-27T12:12:12.000Z', regexp_replace (regexp_replace('2016-05-27T12:12:12.000Z','([][)(}{:.$*+?,|^\-])'),'[0-9]') from dual </code></pre>
Searching a PHP states array for beginning values <p>So I'm sure my solution is an easy one, but it just seems to escape me. I have a basic webpage where a user needs to be able to type in a beginning string of a state, hit search, and the page will output all of the states that begin with that string.</p> <p>For example, if "co" was entered, then Colorado and Connecticut would be displayed, with the input case insensitive if possible. This inpt string should be able to be any length. I am using an array of $states to hold all 50 states that need to be searched. Below is what the basic form looks like.</p> <pre><code>&lt;h1&gt;Search States&lt;/h1&gt; &lt;form method = "post" action = "states.php"&gt; &lt;p&gt;Search: &lt;input type="text" name="search"&gt;&lt;/p&gt; &lt;p&gt;&lt;input type = "submit" value = "Submit"&gt;&lt;/p&gt; &lt;/form&gt; &lt;?php $states = array('Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', etc, etc. </code></pre> <p>I assumed that some kind of regular expression search is what I am looking for, but I can't find how to produce one based off of input and using more than one character at times.</p> <p>Thank you!</p>
<p>Use this</p> <pre><code>$arr = array(); $search_str = 'Co'; foreach($states as $key =&gt; $value){ $strlen = strlen($search_str); if(strtolower(substr($value, 0, $strlen)) == strtolower($search_str)){ $arr[] = $value; } } print_r($arr); </code></pre>
PHP SQL / multible select request / slow <p>I have 2 requests on a SQL database. It takes really long to load the whole script / page. Is there a better (faster) way? My code looks like this</p> <pre><code> $abfrage = "SELECT * FROM table_a WHERE state = '0' ORDER BY EDIT DESC"; $stmt = $pdo-&gt;query($abfrage); foreach($stmt as $data) { ?&gt; $usern = $data['user_name']; $stmt = $pdo-&gt;query("SELECT * FROM tabl_b WHERE user_name = '$usern' ORDER BY follower DESC Limit 1"); $stmt-&gt;execute(); $pl = $stmt-&gt;fetch(); &lt;?php echo $data['ID'];?&gt; &lt;?php echo $data['ID'];?&gt; &lt;?php if ($data['company'] == '') { ?&gt; &lt;a href="https://open.spotify.com/user/&lt;?php echo $data['user_name'];?&gt;" target="_blank"&gt;&lt;?php if ($data['state'] == '3') { echo "&lt;span style=\"color:#0000FF\";&gt;".$data['user_name']."&lt;/span&gt;"; } else { echo $data['user_name'];}?&gt;&lt;/a&gt; &lt;?php } else {?&gt; &lt;a href="https://open.spotify.com/user/&lt;?php echo $data['user_name'];?&gt;" target="_blank"&gt;&lt;?php if ($data['state'] == '3') { echo "&lt;span style=\"color:#0000FF\";&gt;".$data['company']."&lt;/span&gt;"; } else { echo $data['company'];}?&gt;&lt;/a&gt; &lt;?php } ?&gt; &lt;?php echo $data['PL_read'];?&gt; &lt;?php echo $data['PL_total'];?&gt; &lt;?php echo $data['country'];?&gt; &lt;?php echo $data['EDIT'];?&gt; &lt;?php echo $pl['follower'];?&gt; &lt;?php } ?&gt; </code></pre> <p>I have a table around th echo data. I would be great if someone can give me a tip.</p>
<p>First if tables have relation I suggest you to take the data in a single call with join.</p> <pre><code>SELECT * FROM table_a a LEFT JOIN tabl_b b ON a.user_name = b.user_name WHERE a.state = '0' </code></pre> <p>Second for speeding up the things you can put INDEX on the two fields that you are using in the WHERE clause - state, user_name</p> <pre><code>ALTER TABLE `table_a` ADD INDEX `state` (`state`) ALTER TABLE `tabl_b` ADD INDEX `user_name` (`user_name`) </code></pre>
Create full VPC using salt stack and boto.vpc <p>I am able to create VPCs in AWS using salt states, using boto.vpc. But I also need to create create (in addition to the VPC itself) subnets, internet gateways, route tables based on the original VPC that I'm able to create.</p> <p>So if the VPC definition looks like this: </p> <pre><code> Create VPC: boto_vpc.present: - name: dlab-new - cidr_block: 10.0.0.1/24 - dns_hostnames: True - region: us-east-1 - keyid: keyid - key: key </code></pre> <p>How can I refer to the original VPC in subsequent parts of the VPC config? Since I won't know the vpc_id of the VPC until it's created. Is there a variable I could use in subsequent definitions of subnets, IGWs and route tables using a variable?</p> <pre><code>Create subnet: boto_vpc.subnet_present: - name: dlab-new-subnet - vpc_id: ????? - cidr_block: 10.0.0.1/24 - region: us-east-1 - keyid: keyid - key: key Create internet gateway: boto_vpc.internet_gateway_present: - name: dlab-igw - vpc_name: ???? - keyid: keyid - key: key Create route: boto_vpc.route_table_present: - name: my_route_table - vpc_id: ??? - routes: - destination_cidr_block: 10.0.0.1/24 instance_id: i-123456 - subnet_names: - dlab-new-subnet - region: us-east-1 - profile: keyid: keyid key: key </code></pre> <p>Is there any way to use a variable in place of the - vpc_id value that would allow the definitions for subnet, IGW etc to get the name of the VPC generated by the Create VPC process?</p>
<p>In order to get the VPC id of an existing VPC you can use <a href="https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.boto_vpc.html#salt.modules.boto_vpc.get_id" rel="nofollow">boto_vpc execution module</a></p> <p>The first part of your state will create a VPC with the name <code>dlab-new</code> then you can test this from the command line <code>salt minion_name boto_vpc.get_id dlab-new</code> which will return the VPC id if it finds a match.</p> <p>Execution modules can be called within States like this:</p> <pre><code>{% set vpc_id = salt.boto_vpc.get_id(name='dlab-new', region='us-east-1', keyid=keyid, key=key)['id'] %} </code></pre> <p>More info and examples <a href="https://docs.saltstack.com/en/latest/topics/jinja/index.html#jinja-in-states" rel="nofollow">JINJA IN STATES</a></p> <ul> <li><code>vpc_id</code> variable will hold the result which will be the VPC Id of <code>dlab-new</code> in this case and then you can pass it to the other states.</li> <li>VPC name, region, aws keys and others can be set as variables at the top of your state for easier modification in the future instead of go through the whole state looking for them.</li> <li>In order to get the vpc_id correctly you will need to create the VPC using the execution module because the jinja code will be evaluated first.</li> </ul> <p>The full state should be like this one</p> <pre><code>{% set custom_vpc_name = 'dlab-new' %} {% set custom_keyid = keyid %} {% set custom_key = key %} {% set custom_region = 'us-east-1' %} {% set cidr_block = '10.0.0.1/24' %} {% set instance_id = 'i-123456' %} {% set create_vpc = salt.boto_vpc.create(vpc_name=custom_vpc_name,cidr_block=cidr_block,enable_dns_hostnames=True,region=custom_region,keyid=custom_keyid,key=custom_key) %} #this line is using boto_vpc execution module and get_id function which will return the VPC id if a match is found and your vpc will be created as described above with the name 'dlab-new' {% set vpc_id = salt.boto_vpc.get_id(name=custom_vpc_name, region=custom_region, keyid=custom_keyid, key=custom_key)['id'] %} Create subnet: boto_vpc.subnet_present: - name: {{ custom_vpc_name }}-subnet - vpc_id: {{ vpc_id }} - cidr_block: {{ cidr_block }} - region: {{ custom_region }} - keyid: {{ custom_keyid }} - key: {{ custom_key }} Create internet gateway: boto_vpc.internet_gateway_present: - name: {{ custom_vpc_name }}-igw - vpc_id: {{ vpc_id }} # I have changed this line from vpc_name into vpc_id, is that what you meant ? - keyid: {{ custom_keyid }} - key: {{ custom_key }} Create route: boto_vpc.route_table_present: - name: my_route_table - vpc_id: {{ vpc_id }} - routes: - destination_cidr_block: {{ cidr_block }} instance_id: {{ instance_id }} - subnet_names: - {{ custom_vpc_name }}-subnet - region: {{ custom_region }} - profile: keyid: {{ custom_keyid }} key: {{ custom_key }} </code></pre> <p>This is untested code but I have done similar states like this using Salt.</p>
Reduce length of bootstrap pagination buttons <p>I'm using bootstrap in the whole document, I'm using it for the pagination too.</p> <p>This link is awesome: <a href="http://stackoverflow.com/questions/2616697/php-mysql-pagination">PHP &amp; MySQL Pagination</a> and it helped me a lot coding the method for pagination (I am using postgre, I changed a few things).</p> <p>When I print each button for the pagination, I am using bootstrap's code: <a href="http://www.w3schools.com/bootstrap/bootstrap_pagination.asp" rel="nofollow">http://www.w3schools.com/bootstrap/bootstrap_pagination.asp</a></p> <pre><code>&lt;ul class=\"pagination pagination-sm\"&gt;$links&lt;/ul&gt; </code></pre> <p>and:</p> <pre><code>$links .= ($i != $page ) ? "&lt;li&gt;&lt;a href='$explode[0]$final$i'&gt;$i&lt;/a&gt;&lt;li&gt; " : ""; </code></pre> <p>for concatenating new strings to the $links variable(of course first this then echoing $links).</p> <p>Note: I am using explode() because I get my URL and I fix the the <code>&amp;page=</code></p> <p><strong>My question is</strong>:</p> <p>How do I shorten the number of buttons to show per page?</p> <p>At the moment my situation is the one in the screenshot. I'd love to get something like:</p> <pre><code>[current][2][3][4][5]...[61][62] </code></pre> <p><strong>EDIT</strong>:</p> <p>I changed the code to have the "current":</p> <pre><code> if ($i != $page) { $links.="&lt;li&gt;&lt;a href='$explode[0]$final$i'&gt;$i&lt;/a&gt;&lt;li&gt;"; } else { $links.="&lt;li class=\"active\"&gt;&lt;a href='#'&gt;current&lt;/a&gt;&lt;li&gt;"; } } </code></pre> <p><strong>EDIT</strong>:</p> <p>added new image thanks to 1st solution (it is now black because I changed theme in the meantime).</p> <p><strong>EDIT</strong>: adding the php code.</p> <pre><code>$perPage = addslashes(strip_tags(@$_GET["perPage"])); $page = addslashes(strip_tags(@$_GET['page'])) ?: '1'; $startAt = $perPage * ($page - 1); SWITCH ($direction){ case "SENT": $count = "SELECT count(*) as total, 'SENT' as direction FROM sent WHERE date &gt;= '$fdate' AND date &lt;= '$tdate' AND identification LIKE '%$identification%' "; $query = "SELECT *,'SENT' as direction FROM sent WHERE date &gt;= '$fdate' AND date &lt;= '$tdate' AND identification LIKE '%$identification%' "; break; } $res = pg_fetch_assoc(pg_query($conn, $count)); $total = ceil($res['total'] / $perPage); if (empty($total1)) { $total1 = '0'; } else { $total1 = ceil($res['total1'] / $perPage); } $totalPages = $total + $total1; $links = ""; $absolute_url = full_url( $_SERVER ); for ($i = 1; $i &lt;= $totalPages; $i++) { $explode = explode("&amp;page=", $absolute_url); $final="&amp;page="; if ($i != $page) { $links.="&lt;li&gt;&lt;a href='$explode[0]$final$i'&gt;$i&lt;/a&gt;&lt;li&gt;"; } else { $links.="&lt;li class=\"active\"&gt;&lt;a href='#'&gt;current&lt;/a&gt;&lt;li&gt;"; } } $query .= "order by date DESC OFFSET '$startAt' LIMIT '$perPage' "; $result = pg_query($conn, $query); </code></pre> <p><strong>EDIT: Found the problem in the jquery:</strong> it will not load, never, but when I call the function at the document=ready status, it will.</p> <pre><code> &lt;script&gt; $(document).ready(function(){ $('#paginateblock').css('margin-left','-110px'); }); &lt;/script&gt; </code></pre> <p>I need this to work always, not only when the document is "ready", rather, at every click on 'paginateblock' or everytime I change page.</p> <p>Anybody can help?</p> <p><strong>SOLUTION #1:</strong> Thanks to the help of <strong>S Gandhe</strong> that provided me his code, I'm copying it here with my correction.</p> <pre><code>for ($i = 1; $i &lt;= $totalPages; $i++) { if($page &gt;= 7){ $start = $page -4; } else { $start = $i; } $end = ($start + 7 &lt; $totalPages)?($start + 7):$totalPages; for ($start; $start &lt;= $end ; $start++) { $explode = explode("&amp;page=", $absolute_url); $final="&amp;page="; $css_class = ($page == $start ) ? "class='active'" : ""; $links .= "&lt;li&gt;&lt;a href='$explode[0]$final$start'&gt;$start&lt;/a&gt;&lt;li&gt;"; } } </code></pre> <p><strong>CSS:</strong> [the css for <code>&lt;li&gt;</code> did not change] </p> <pre><code>#page-selection{ width:350px; height:36px; overflow:hidden; } </code></pre> <p><strong>HTML/PHP</strong></p> <pre><code>&lt;div id="page-selection"&gt;&lt;?php echo "&lt;ul class=\"pagination pagination-sm\"&gt;$links&lt;/ul&gt;"; ?&gt;&lt;/div&gt; </code></pre> <p><strong>SOLUTION #2 - FINAL:</strong> I modified the code a bit more, the pagination buttons are inside a <code>&lt;div&gt;</code> and the content is aligned. Plus, Page #1 and #lastpage are always shown.</p> <p><strong>CODE:</strong></p> <pre><code>for ($i = 1; $i &lt;= $totalPages; $i++) { if($page &gt;= 4){ $start = $page -3; } else { $start = $i; } $end = ($start + 6 &lt; $totalPages)?($start + 6):$totalPages; for ($start; $start &lt;= $end ; $start++) { $explode = explode("&amp;page=", $absolute_url); $final="&amp;page="; $css_class = ($page == $start ) ? "class='active'" : ""; $links .= "&lt;li&gt;&lt;a href='$explode[0]$final$start'&gt;$start&lt;/a&gt;&lt;/li&gt;"; } $firstpage = "&lt;li&gt;&lt;a href='$explode[0]$final'1&gt;&lt;&lt;&lt;/a&gt;&lt;/li&gt;"; $lastpage = "&lt;li&gt;&lt;a href='$explode[0]$final$totalPages'&gt;&gt;&gt;&lt;/a&gt;&lt;/li&gt;"; } </code></pre> <p><strong>HTML:</strong></p> <pre><code> &lt;div id="page-selector"&gt; &lt;div class="page-selector-field"&gt;&lt;?php echo "&lt;ul class=\"pagination pagination-sm\"&gt;$firstpage&lt;/ul&gt;"; ?&gt;&lt;/div&gt; &lt;div id="page-selection" class="page-selector-field"&gt;&lt;?php echo "&lt;ul class=\"pagination pagination-sm\"&gt;$links&lt;/ul&gt;"; ?&gt;&lt;/div&gt; &lt;div class="page-selector-field"&gt;&lt;?php echo "&lt;ul class=\"pagination pagination-sm\"&gt;$lastpage&lt;/ul&gt;"; ?&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS:</strong></p> <pre><code>#page-selection{ width:344px; height:36px; overflow:hidden; } #page-selector{ width: 450px; height:36px; overflow:hidden; /*margin: 0 auto; uncomment this if you want this bar centered */ } .page-selector-field{ width:50px; height:36px; overflow:hidden; float: left; } ul.pagination { display: inline-block; padding: 0; margin: 0; } ul.pagination li { display: inline; width: 50px; } ul.pagination li a { display: block; width: 50px; text-align:center; float: left; padding: 8px 16px; text-decoration: none; } </code></pre> <p><a href="https://i.stack.imgur.com/qcS4T.png" rel="nofollow"><img src="https://i.stack.imgur.com/qcS4T.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/CrPXa.png" rel="nofollow"><img src="https://i.stack.imgur.com/CrPXa.png" alt="enter image description here"></a></p>
<p>am not sure about the quality/performance of code, but you can do it multiple ways, 2 of them here. I actually started using lazy load and auto loading of pages when scroll rather page numbers, so I don't have the code.</p> <p>1) JS/CSS:You can create a fix width div for page numbers and scroll to current page using current page number * each div width. let's say your current page is 54 and each page number is taking 50px. you will set the margin left to -2000px something.</p> <pre><code>$('#paginateblock').css('margin-left','-110px'); </code></pre> <p><a href="https://jsfiddle.net/66wy0t19/3/" rel="nofollow">https://jsfiddle.net/66wy0t19/3/</a></p> <p>2) PHP : as you said you have the links in array. you can use array_splice to get just the 10 links based on current page number. so if it's 54. you will may be spice it from 50-60 for showing 10.</p> <ul> <li>now you will need 2 buttons. one to move the page numbers div and second to get to Next page (like 4th from 3rd).</li> </ul> <p><strong>Update:</strong> Couldn't find the js code, but here is some code based on php solution. one minor advantage is you won't print all 100 items on page rather just print 5 links.</p> <pre><code>echo "&lt;ul class='pagination wrap'&gt;"; if ($this-&gt;pageNumber - 1) { echo "&lt;li &gt;&lt;a href='{$this-&gt;url}/page_" . ($this-&gt;pageNumber - 1) . "/' {$ajax_request}&gt;&lt;&lt;&lt;/a&gt;&lt;/li&gt;"; } $start =($this-&gt;pageNumber &gt; 5)?$this-&gt;pageNumber -4:1; $end = ($i + 5 &lt; $this-&gt;total_pages)?($start+5):$this-&gt;total_pages; for ($start; $start &lt;= $end ; $start++) { echo "&lt;li {$css_class}&gt;&lt;a href='{$this-&gt;url}/page_{$i}/' {$ajax_request} &gt;{$i}&lt;/a&gt;&lt;/li&gt;"; } if ($this-&gt;total_pages - $this-&gt;pageNumber &gt; 1) { echo "&lt;li &gt;&lt;a href='{$this-&gt;url}/page_" . ($this-&gt;pageNumber + 1) . "/' {$ajax_request}&gt;&gt;&gt;&lt;/a&gt;&lt;/li&gt;"; } echo "&lt;/ul&gt;";[![the output looks like this. ofcourse with classes. but i use bootstrap too.][1]][1] </code></pre> <p><a href="https://i.stack.imgur.com/U80qG.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/U80qG.jpg" alt="enter image description here"></a></p> <p><strong>Update 2:</strong> Assuming each page number is taking 50px. this should work. </p> <pre><code>var currentPage =27; var paginateBlockMargin = (Math.ceil(currentPage/2) * 100)-100; $('#paginateblock').css('margin-left', '-'+paginateBlockMargin+'px'); Check t https://jsfiddle.net/66wy0t19/14/ </code></pre> <p>This is the PHP code using your variables. You would need to replace your for loop with following. Prefer PHP code, as you will still need a lot of consideration in above JS. I wish I could find that JS code I had. sad.</p> <pre><code>if($page &gt; 5){ $start = $page -4; } $end = ($start + 5 &lt; $totalPages)?($start + 5):$totalPages; for ($start; $start &lt;= $end ; $start++) { $explode = explode("&amp;page=", $absolute_url); $final="&amp;page="; $css_class = ($page == $start ) ? "class='active'" : ""; $links .= "&lt;li&gt;&lt;a href='$explode[0]$final$start'&gt;$start&lt;/a&gt;&lt;li&gt;"; } </code></pre>
Python handle 'NoneType' object has no attribute 'find_all' error with if else statement <p>I am using beautifulsoup4 to grab stock data and send to a spreadsheet in python. The problem I am having is that I cannot get my loop to skip over attributes that return None. So what I am needing is the code to add null values to rows where attribute would return none.</p> <pre><code>//my dictionay for storing data data = { 'Fiscal Quarter End' : [], 'Date Reported' : [], 'Earnings Per Share' : [], 'Consensus EPS* Forecast' : [], '% Surprise' : [] } url = "" html = requests.get(url) data = html.text soup = bs4.BeautifulSoup(data) table = soup.find("div", class_="genTable") for row in table.find_all('tr')[1:]: if row.has_attr('tr'): cols = row.find_all("td") data['Fiscal Quarter End'].append( cols[0].get_text() ) data['Date Reported'].append( cols[1].get_text() ) data['Earnings Per Share'].append( cols[2].get_text() ) data['Consensus EPS* Forecast'].append( cols[3].get_text() ) data['% Surprise'].append( cols[4].get_text() ) else: //where i need to add in the empty 'n/a' values data['Fiscal Quarter End'].append() data['Date Reported'].append() data['Earnings Per Share'].append() data['Consensus EPS* Forecast'].append() data['% Surprise'].append() </code></pre>
<p>You have used the <code>data</code> variable for two different things. The second usage overwrote your dictionary. It is simpler to just use <code>html.text</code> in the call to <code>soup.find()</code>. Try the following:</p> <pre><code>import requests import bs4 # My dictionary for storing data data = { 'Fiscal Quarter End' : [], 'Date Reported' : [], 'Earnings Per Share' : [], 'Consensus EPS* Forecast' : [], '% Surprise' : [] } empty = 'n/a' url = "" html = requests.get(url) soup = bs4.BeautifulSoup(html.text, "html.parser") table = soup.find("div", class_="genTable") rows = [] if table: rows = table.find_all('tr')[1:] for row in rows: cols = row.find_all("td") data['Fiscal Quarter End'].append(cols[0].get_text()) data['Date Reported'].append(cols[1].get_text()) data['Earnings Per Share'].append(cols[2].get_text()) data['Consensus EPS* Forecast'].append(cols[3].get_text()) data['% Surprise'].append(cols[4].get_text()) if len(rows) == 0: # Add in the empty 'n/a' values if no columns found data['Fiscal Quarter End'].append(empty) data['Date Reported'].append(empty) data['Earnings Per Share'].append(empty) data['Consensus EPS* Forecast'].append(empty) data['% Surprise'].append(empty) </code></pre> <p>In the event the <code>table</code> or <code>rows</code> was empty, <code>data</code> would hold the following:</p> <pre><code>{'Date Reported': ['n/a'], 'Earnings Per Share': ['n/a'], '% Surprise': ['n/a'], 'Consensus EPS* Forecast': ['n/a'], 'Fiscal Quarter End': ['n/a']} </code></pre>
Why can't I commit changes in a conflicted state? <p>As we all know, merging branches in subversion (or any other revision control system for that matter) every so often results in conflicts. Somtimes these conflicts can be very complicated to resolve. Yet you are required to do so before committing the changes to the repository. </p> <p>As the merge itself obviously will apply a set of changes, any modifications to resolve the conflicts will be applied on top of these. In the end it is impossible to separate the changes from the automatic merge from the manual modifications applied to resolve the conflicts.</p> <p>It is not uncommon that issues are introduced when merging, not only due the challenge of integration itself, but from incorrect decisions when resolving merge conflicts. It would be easier to track these issues down fast if the decisions made when resolving any conflicts were clearly visible in a separate commit. It would also be easier to have a colleague review what you have done to resolve the conflicts.</p> <p>This would be possible if committing changes in a conflicted state would be allowed. The automatic merge including conflicts could be committed first and conflict resolution afterwards.</p> <p>Obviously you could argue that it is undesired to have a repository in a conflicted state, but you could always have the client access a last-unconflicted-revision. I would rather have a repository in a conflicted state every once in a while, instead of a repository broken by incorrect merge resolution.</p> <p>Are there any reasons why can't I commit changes in a conflicted state?</p> <p>Optional: Am I missing some subversion magic, are there tools to find out what decisions were made to resolve conflicts?</p> <p>Optional: Does git or any other revision handling system handle this better than subversion?</p>
<p>Think about what it would <em>mean</em> for your repository to be in a conflicted state. What that means is that there is more than one possible correct latest version of the code, which means that you have forked the repository. Source control systems already have means by which a repository can be forked.</p> <p>If you really don't know what the solution to the merge conflict is, you are forking your code, so you should do a proper fork and not try to implement some sort of pseudo or quasi-fork into your source control system!</p>
Where are the ASP.NET core symbols hosted? <p>Have the .NET / ASP.NET core symbols been hosted anywhere yet? They would be helpful in debugging and learning.</p>
<p>To debug Asp.Net Core, I followed the article sbouaked is mentionning, got the source from Git, and it's working perfectly. Didn't find a way to get only the symbols.</p>
openpyxl read formula value without changing formula <p>I want to read the formula value in an xlsx file, write the value in another cell and store the xlsx file.</p> <p>I'm using the data_only mode</p> <pre><code>excelDoc = openpyxl.load_workbook(clientFile, data_only=True) </code></pre> <p>to read the formula value. But when I save the file all formulas are overriden by their values.</p> <p>How can I prevent that?</p>
<p>You can't. You can either have the values or the formulae.</p>