text:
Q: Could not add dynamic data to the DataModel in java I'm trying to add dynamic items in Object[][] but it throws array index out of bound exception. I'm using the below code to do this,
private static final int CHECK_COL = 1;
    private final Object[][] DATA = {};
    private final String[] COLUMNS = { "Customer", "Selected Customer" };
    private DataModel dataModel;
    private JTable table;
    private DefaultListSelectionModel selectionModel;

ArrayList<String> items = new ArrayList<String>();
        JSONParser parser = new JSONParser();
        try {

            Object obj = null;
            try {
                obj = parser.parse(new FileReader(new File("json/customer_list.json")));
            } catch (org.json.simple.parser.ParseException e1) {
                e1.printStackTrace();
            }
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray listOfBranches = (JSONArray) jsonObject.get("customers");
            for (int i = 0; i < listOfBranches.size(); i++) {
                JSONObject item = (JSONObject)listOfBranches.get(i);
                Set keys = item.keySet();
                Iterator a = keys.iterator();
                while(a.hasNext()) {
                    String key = (String)a.next();
                    System.out.print("key : "+key);
                    items.add(key);
                }
                System.out.println("Customer :" + listOfBranches.get(i)+"\n item "+item);
            }

            System.out.println("items array size :" + items.size());

            String[] customerArr = new String[items.size()];
            customerArr = items.toArray(customerArr);

            System.out.println("customerArr array size :" + customerArr.length);
            for (int i = 0; i < customerArr.length; i++) {
                System.out.println("customerArr array size :" + customerArr.length);
                    DATA[i] = new Object[]{customerArr[i], Boolean.FALSE};
                    dataModel = new DataModel(DATA, COLUMNS);
                    table = new JTable(dataModel);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Getting array index out of bound exception in this below line,
DATA[i] = new Object[]{customerArr[i], Boolean.FALSE};
Could you please suggest me an idea to do this? Thanks in advance.

A: The index out of bounds exception you are getting is, as you pointed out, due to the following line:
DATA[i] = new Object[] { customerArr[i], Boolean.FALSE };

The problem here is the first dimension of the DATA array was never initialized, and so has a capacity of zero.  To resolve this, initialize your 2D array with the proper dimensions:
DATA = new Object[customerArr.length][];

Also, you are assigning only a single string to each row of your DATA 2D object array.  Perhaps this is not what you intended, but I would have expected an assignment along these lines:
DATA[i] = // some 1D array


text:
Q: How do you remove health of multiple enemies? using System.Collections;

public class TowerAttack : MonoBehaviour {

public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;

GameObject player;
PlayerHealth playerHealth;
bool playerInRange;
float timer;

void Awake()
{
    player = GameObject.FindGameObjectWithTag ("Player");
    playerHealth = player.GetComponent<PlayerHealth> ();

}

void OnTriggerEnter(Collider other)
{
    print (other);
    if (other.gameObject == player)
        playerInRange = true;
}

void OnTriggerExit(Collider other)
{
    if (other.gameObject == player)
        playerInRange = false;
}

// Update is called once per frame
void Update () {

    timer += Time.deltaTime;

    if (timer >= timeBetweenAttacks && playerInRange)
        Attack ();
    if (playerHealth.currentHealth <= 0)
        print ("Player's dead");
}

void Attack()
{
    timer = 0f;
    print (playerHealth);
    if (playerHealth.currentHealth > 0)
        playerHealth.TakeDamage (attackDamage);
}
}

I am using this code on an object called tower and it has box collider with istrigger active. There are multiple objects spawn on the field with "PlayerHealth" script attached and tagged as "Player". However only the first "Player" which enter the box collider get its health remove and the rest of the "Player" objects stay healthy.

A:
There are multiple objects spawn on the field with "PlayerHealth"
  script attached and tagged as "Player". However only the first
  "Player" which enter the box collider get its health remove and the
  rest of the "Player" objects stay healthy.

The playerHealth = player.GetComponent<PlayerHealth> (); line of code will only get the PlayerHealth from one object only.
To remove health from multiple enemies, you need to perform other.GetComponent<PlayerHealth> () each time OnTriggerEnter is called.
void OnTriggerEnter(Collider other)
{
    print(other);
    //Remove health only if the Object is tagged as Player
    if (other.CompareTag("Player"))
    {
        other.GetComponent<PlayerHealth>().TakeDamage(attackDamage);
        playerInRange = true;
    }
}

A: player = GameObject.FindGameObjectWithTag ("Player");

This is for setting one player. If there are multiple player, one of players is set to the variable. playerHealth = player.GetComponent<PlayerHealth> (); is also only the player. You should do like below.
using System.Collections;

public class TowerAttack : MonoBehaviour
{
    public float timeBetweenAttacks = 0.5f;
    public int attackDamage = 10;

    GameObject[] players;
    bool playerInRange;
    float timer;

    void Awake()
    {
        players = GameObject.FindGameObjectsWithTag ("Player");
        // FindGameObjectWithTag => FindGameObjectsWithTag
    }

    void OnTriggerEnter(Collider other)
    {
        print (other);
        if (other.tag == "Player")
            playerInRange = true;
    }

    void OnTriggerExit(Collider other)
    {
        if (other.tag == "Player")
            playerInRange = false;
    }

    void Update ()
    {
        timer += Time.deltaTime;

        if (timer >= timeBetweenAttacks && playerInRange)
            Attack ();
        for (int i = 0; i < players.Length; i++)
        {
            if (players [i].GetComponent<PlayerHealth> ().currentHealth <= 0)
                print ("Player's dead")
        }
    }

    void Attack()
    {
        timer = 0f;
        print (playerHealth);
        if (playerHealth.currentHealth > 0)
            playerHealth.TakeDamage (attackDamage);
    }
}

If you want to make the TowerAttack Attack() all players in range at the same time, you can apply the code above. But, if you want to attack players one after another, move the function in Update() to OnTrigger* methods. Then you may need this method OnTriggerStay.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use a function to build an array? I am a little rusty on my PHP and I am trying to create a function that will build an array. Essentially, I am trying to have an associative array of contacts ($contacts), with each individual element being a separate array ($contact). For starters, I would like it to be able to have a UniqueID,FirstName,and LastName within the elements. Here is the direction I am heading in right now:
    <?php

$contact=array();
function createContact($Unique_ID,$FirstName,$LastName){
global $contact;
$contact=array("Unique_ID"=>$Unique_ID,"First_Name"=>$FirstName,"Last_Name"=>$LastName);
};
createContact("123456","John","Smith");
createContact("654321","Jane","Doe");
createContact("331143","Steve","Sample");

foreach($contact as $key=>$value){
echo $key.",",$value."
";
};

?>

This should create the $contact array with 3 separate records, but it only adds the last entry (In this case Steve Sample because it is the last one that was run). I remember learning somewhat about the global variables, but I think I am using it incorrectly. After I solve this, I will find a way to make an array containing all of these arrays.

A: You are overwriting the array $contact every time you invoke createContact().
You have to append the new records
function createContact($Unique_ID,$FirstName,$LastName){
    $contact[] = array("Unique_ID" => $Unique_ID, "First_Name" => $FirstName, "Last_Name" => $LastName);
};

Note the [] to indicate that you want to append another entry.
If you want to print these you probably want to do something like this
foreach ($contact as $item) {
    echo "ID = " . $item["Unique_ID"] . "
";
    echo "First name = " . $item["First_Name"] . "
";
    echo "Last name = " . $item["Last_Name"] . "
";
}

A: You need additional array.
$final_array = array();

and use
array_push($final_array, $contact);

inside the createContact function


text:
Q: How do I access the returned value of a Java Request in JMeter? I'm trying to create a simple test plan in JMeter to send data over JMS, using a Publisher and a Subscriber. I've got a Java Request which returns a SampleResult object containing a list of subresults, each containing a String ("Hello, world!" + count), and I want to be able to send these Strings over JMS, but I can't work out how to access them.
Everything is working fine in isolation, but how can I plug the result that my Java Request spits out into my Publisher so it can be sent?

A: Add a Regular Expression Extractor as a child of your Java Request:

You can then use this in your JMS Sampler:

${data}


text:
Q: Creating dynamic span How can I create dynamic tags?
$("").attr({
    id: "image-1",
    src: "/images/flower.png",
}).appendTo("#" + imgContainer);

It will create
I want to create  tag around  tag.
i.e.

A: You can use wrap():
$("").attr({
    id: "image-1",
    src: "/images/flower.png"
}).appendTo("#" + imgContainer).wrap("")

A: You can use wrap() to wrap one element inside another. For example:
$("").attr({
    id: "image-1",
    src: "/images/flower.png",
})
.appendTo("#" + imgContainer)
.wrap("");

A: DOM operations are oh-so-expensive; just prepare the markup you're after and then append it as needed!
//Before:
$("")                   //#1, create an element outside of the tree
.attr({                        //#2? change its attributes
  id: "image-1",
  src: "/images/flower.png"
})
.appendTo("#" + imgContainer)  //#3, add the element to DOM
.wrap("");             //#4, create and add another element to DOM

//After:
$('')  //#1
.appendTo("#" + imgContainer);                                 //#2

Here is a jsperf test case which results in ~5K ops/sec for the first case and ~14K for the latter (on my pretty decent box).
This is not premature optimization, either. If you have, for instance, ajax-populated 7x10 table and you create every cell individually... and wrap them into
 elements... and then add it to a table, the overhead adds up. Operate on a string and your script will be at least 80 times faster!
Another aspect to remember is that jsperf explicitly measures javascript performance only. If you're manipulating a table, its content will be even more aggressively re-painted/re-flown.


text:
Q: Divide a .wav file according to the video frame rate in Matlab I have a yuv  video (say stream.yuv) and the corresponding audio file (stream.wav). Now I have GUI which renders the raw video on a frame by frame basis. The problem I am currently facing is that I need to play the audio associated with each video frame.
I've tried the following to begin with, but when I execute this, the audio sounds chop
%% Dividing the audio into per-second samples
nframes = 720;
[audioFile, audioSampleFreq] = audioread('stream.wav');
numSamples = length(audioFile);
audioLength = round(numSamples / audioSampleFreq);

for frame = 1:audioLength
    start = (frame-1)*audioSampleFreq+1;
    stop = frame*audioSampleFreq;
    [start stop]
    audioFrame1 = audioFile(start:stop,:);
    sound(audioFrame1,audioSampleFreq);
end

To divide the audio into samples per video frame,
    audioFileName = 'stream.wav';
    nframes = 720;
    framerate = 25;
    [audioFile, audioSampleFreq] = audioread(audioFileName);

    audioFRate = round(audioSampleFreq/framerate);

    %% Total number of audio samples
    numSamples = length(audioFile);

    %% number of audio frames
    numFrames = floor(numSamples/audioFRate);

    for frame = 1:numFrames
        start = (frame-1)*audioFRate+1;
        stop = frame*audioFRate;
        [start stop]
        audioFrame1 = audioFile(start:stop,:);
        sound(audioFrame1,audioSampleFreq);
    end

Any thoughts on how to synchronize the per-frame rendering of the YUV frames and the per-second audio samples? Thanks!

A: I think you approached the problem the wrong way round. Adapting your audio signal to the video signal is typically the wrong way round because small disruptions in a audio stream are very noticeable, while the average viewer does not notice missing frames.
Instead, synchronize your video signal to the audio signal. To get a quick start, set up a audio player and start with some code like this:
videorate=25 %fps
audiorate=audio.SampleRate %sample rate
while audio.isplaying()
   displayFrame(ceil(audio.CurrentSample/audiorate*videorate))
end

There is much which can be improved but I assume this simple implementation will already show better results than your current attempt.
Things to improve

*

*Don't render the same frame twice.

*The ceil is just a quick and dirty approximation. Instead you need to call your displayFrame for frame f at time f/fps-processing_delay where processing_delay is the time between calling displayFrame and the image actually appearing on the screen. Set it to 1/25 initially and tweak it manually if audio and video seems to be not synchronized.

*When missing the time where you should call displayFrame make a decision. For small times still display frame, for larger gaps drop the frame and continue with the next one. Maybe pause to display not to early.

*When your Video signal really messes up, e.g. dropping 15 out of the last 25 frames, check for possible causes. Processing high resolution raw video, this typically happens because your HDD is to slow, so pausing both video and audio for a short time should allow the buffers to fill up again.

An alternative to this approach are approaches using variable playback speed, slightly adjusting the audio and video playback speed to get both synchronized. I assume that such approaches won't succeed in Matlab because you need to process your data with very low latencies to get this approach done.


text:
Q: Remove dash between strings and Capitalize the String in Javascript I am trying to capitalize the String after removing all dashes in between.
so this i-am-string would become I am string.
This is what I tried, but it does capitalize, but I don't know how to remove dashes and capitalize.
function tweakFunction (string) {

     return string.charAt(0).toUpperCase() + string.slice(1);
}

Thanks

A: function tweakFunction(str) {
   str = str.replace(/-/g, ' ');
   return str.charAt(0).toUpperCase() + str.slice(1);
}
console.log(tweakFunction('i-am-string')); //=> "I am string"

A: You could use a couple regex, like in the PHP version you previously posted:
var result = str
  .replace(/-/g, ' ')
  .replace(/^./, function(x){return x.toUpperCase()})

A: /* Capitalize the first letter of the string and the rest of it to be Lowercase */
function capitalize(word){
    return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase()
}
console.log(capitalize("john")); //John
console.log(capitalize("BRAVO")); //Bravo
console.log(capitalize("BLAne")); //Blane


text:
Q: Jquery code do not see special characters I have a code that filters rows which i get from database query.. It works fine but it does not show the rows which start with a special character like "Ç, Ş, Ö, Ü"..
Forexample if i write Dar to input area it will list Daria, Darian, Dariko, Dartonal but if i write Çar to input area it will show nothing.. How can i fix this in this code? Thank you..
<script>
    var $rows = $('#table tr');
    $('#search').keyup(function() {

        var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
            reg = RegExp(val, 'i'),
            text;

        $rows.show().filter(function() {
            text = $(this).text().replace(/\s+/g, ' ');
            return !reg.test(text);
        }).hide();
    });
</scrpit>


text:
Q: Angular - 'name' attribute for tag 'mat-select' I am creating a form in Angular (see below). The userEntitiesRoles array can change, due to the logic of the page I'm creating. So I need to be sure that I provide a unique name attribute for the tag mat-select, otherwise I get problems. This is the reason why I tried to use a random string, with the Typescript code that is reported below. However, in this way, in the console of Chrome I get the error that you find at the end of the post, and I don't understand why. Do you have any suggestion?
html:
<div *ngFor="let item of userEntitiesRoles">
        <mat-form-field>
          <mat-label>{{'USERS.ROLE' | translate}}</mat-label>
          <mat-select name="role-{{generateRandomString(5)}}" [(ngModel)]="item.role" required>
            <mat-option [value]="optionRole" *ngFor="let optionRole of roleOptions">{{optionRole | uppercase}}</mat-option>
          </mat-select>
        </mat-form-field>
</div>

Typescript:
generateRandomString(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
       result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
 }

error:
ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'zAx5R'. Current value: 'rPFo6'..

A: This is a big enough area. Probably a few hours of research to fully understand.
Basically Angular checks the DOM twice on initialization, first to set the values and the second time to make sure it was correct the first time.
On both occasions generateRandomString(5) will be called and will give a different answer each time.
Angular is afraid that this means you have a problem in your code so you get that error.
It won't happen in production mode but you should probably try to fix it anyway.
One approach:
It's usually better to not use functions in your html because they will be called every time something happens in the DOM (Mouse moves, click, scrolls).
It would be better to have a variable or array of variables that you set in ngOnInit or whenever they need to change.
Then change your html to this:
<div *ngFor="let item of userEntitiesRoles; index as i">
    <mat-form-field>
      <mat-label>{{'USERS.ROLE' | translate}}</mat-label>
      <mat-select name="role-{{myRandomArray[i]}}" [(ngModel)]="item.role" required>
        <mat-option [value]="optionRole" *ngFor="let optionRole of roleOptions">{{optionRole | uppercase}}</mat-option>
      </mat-select>
    </mat-form-field>

Another approach:
Use ChangeDetectorRef and call it in AfterViewInit
constructor(private cd: ChangeDetectorRef) {
}

ngAfterViewInit() {
    this.cd.detectChanges();
}

The second check happens before ngAfterViewInit and cd.detectChanges() tells Angular to go and recheck again.
This works when you have a variable that changes between checks it may not work on a function.
Probably you need to combine both approaches.
I'm not a doctor so some of this might be a bit off.
Here's an article about it AngularInDepth

A: The error mentioned by you occurs when changes are triggered after the angular change detection has completed its check.
The life cycle hooks have completed the execution and then a new change is encountered.
To resolve the issue, you can manually trigger change detection by injecting ChangeDetectorRef (say you name it cdr) in the constructor and then using this.cdr.detectChanges().
This function triggers helps in triggering change detection cycle again manually.


text:
Q: How to set active tab in gnome-terminal? When I open gnome-terminal with multiple tabs from the command line, I would like to preselect (on the command line) which one of the tabs should get focus.
I tried
gnome-terminal --tab -t A --active --tab -t B

to set tab A as the active, but instead tab B becomes the active one.

A: Create the script bellow , make it executable with chmod +x scriptname, where script name is actual script name.
Run the script with 4 parameters. For example, I run it with
activetab.sh TAB-1 TAB-2 TAB-3 TAB-4. You can call tabs anything you want, TAB-1 is just example.
You will be prompted for which tab you want to focus on, type it exactly as you've typed it in the argument
Note: you will need to have wmctrl and xdotool installed for this script to work ! sudo apt-get install wmctrl xdotool
The script
#!/bin/bash
# Author : Serg Kolo
# Date: April 11,2015
# Description: Open gnome-terminal with 4 tabs, and focus on tab with particular name
#
# set -x
echo "Which window to focus ? "
read FOCUS

gnome-terminal --tab -t $1  --tab -t $2  --tab -t  $3 --tab -t $4

if [ $? -eq 0 ]; then
    sleep 0.5
    WINID=$(xprop -root | awk '/_NET_ACTIVE_WINDOW/ && /0x/ {print $5}' | cut -d'x' -f2)

    while [ $(wmctrl -l | grep $WINID | awk '{print $4}') != $FOCUS ]; do
        xdotool key Ctrl+Page_Up
    done

fi

Demo
If you can't see animation bellow, open it in different browser (chromium or google chrome) , or follow this link :  http://i.stack.imgur.com/2sWMb.gif


text:
Q: Code for reading from a text file doesn't work I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.
I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.
I have altered it a bit from what I was given. Here is where I am now:
This is my main class
package textfiles;

import java.io.IOException;

public class FileData {

public static void main(String[] args) throws IOException {

    String file_name = "C:/Users/Desktop/test.txt";

        ReadFile file = new ReadFile(file_name);
        String[] aryLines = file.OpenFile();
        int nLines = file.readLines();
        int i = 0;

    for (i = 0; i < nLines; i++) {
        System.out.println(aryLines[i]);
      }
    }
  }

This is my class that will read the text file and sense the number of lines
package textfiles;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

private String path;

public ReadFile(String file_path) {
    path = file_path;
}
int readLines() throws IOException {

  FileReader file_to_read = new FileReader(path);
  BufferedReader bf = new BufferedReader(file_to_read);

  int numberOfLines = 0;
  String aLine;

  while ((aLine = bf.readLine()) != null) {
  numberOfLines++;
}
bf.close();
return numberOfLines;
}

public String[] OpenFile() throws IOException {

  FileReader fr = new FileReader(path);
  BufferedReader textReader = new BufferedReader(fr);

  int numberOfLines = 0;

  String[] textData = new String[numberOfLines];

  int i;

 for (i = 0; i < numberOfLines; i++) {
    textData[i] = textReader.readLine();
  }

textReader.close();
return textData;
 }
}

Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.

A: The problem is, you set the number of lines to read as zero with int numberOfLines = 0;
I'd rather suggest to use a list for the lines, and then convert it to an array.
public String[] OpenFile() throws IOException {

  FileReader fr = new FileReader(path);
  BufferedReader textReader = new BufferedReader(fr);

  //int numberOfLines = 0; //this is not needed

  List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file

  //this part should work akin to the readLines part
  String aLine;
  while ((aLine = bf.readLine()) != null) {
      textData.add(aLine); //add the line to the list
  }

  textReader.close();
  return textData.toArray(new String[textData.size()]); //convert it to an array, and return
 }
}

A: int numberOfLines = 0;
String[] textData = new String[numberOfLines];

textData is an empty array. The following for loop wont do anything.
Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
   list.add(line);
}
br.close();

I also suggest that you read tutorials on object oriented concepts.

A: This is a class that I wrote awhile back that I think you may find helpful.
public class FileIO {
  static public String getContents(File aFile) {
    StringBuilder contents = new StringBuilder();
    try {
        //use buffering, reading one line at a time
        //FileReader always assumes default encoding is OK!
        BufferedReader input = new BufferedReader(new FileReader(aFile));
        try {
            String line = null; //not declared within while loop
            /*
             * readLine is a bit quirky :
             * it returns the content of a line MINUS the newline.
             * it returns null only for the END of the stream.
             * it returns an empty String if two newlines appear in a row.
             */
            while ((line = input.readLine()) != null) {
                contents.append(line);
                contents.append(System.getProperty("line.separator"));
            }
        } finally {
            input.close();
        }
    } catch (IOException ex) {
    }
    return contents.toString();
}

static public File OpenFile()
{
    return (FileIO.FileDialog("Open"));
}

static private File FileDialog(String buttonText)
{
    String defaultDirectory = System.getProperty("user.dir");
    final JFileChooser jfc = new JFileChooser(defaultDirectory);
    jfc.setMultiSelectionEnabled(false);
    jfc.setApproveButtonText(buttonText);
    if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION)
    {
        return (null);
    }
    File file = jfc.getSelectedFile();
    return (file);
}
}

It is used:
  File file = FileIO.OpenFile();
It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.


text:
Q: jQuery smoothly transition from default image to another image then another I have a unordered list of images with the first li having a "display: list-item" and the rest having a "display: none".
What I want to do is have a smooth transition that fades in the second image then the third without the appearance of a break.
The following jsFiddle shows what I have at the minute, notice there is a break in the fade between the second and third image fade.
http://jsfiddle.net/e6hUr/
Can anyone help please?

A: Maybe you could experiment with different easing functions, the standard one is "swing", you could try "linear"
$('#enter').click(function() {
    $('#slide2').fadeIn(1000, 'linear', function(){
        $('#slide3').fadeIn(1000, 'linear');
    });
});

http://jsfiddle.net/e6hUr/1/

If you use jqueryui there are more easing functions you could try

A: I hope you like this one:
http://jsfiddle.net/e6hUr/4/
I'd try to implement some animation overlapping.


text:
Q: Cisco iOS - Two SSID's , 1 blocking specific URL The routers here broadcast two SSID. One for guest, the other for Company Users. Our users are attempting to access a specific URL but unable to through the Company WiFi. But are able to access the URL through the guest network and when directly connect via Ethernet. This led me to believe this is some ACL issue on the Company WiFi that is blocking it. We do not use a web GUI for our Routers and I am new to Cisco iOS so how would I permit this specific URL? Which access-list does it belong to? Here is the info for the specific SSID / interface:
interface Dot11Radio1.1
 encapsulation dot1Q 1 native
 no ip route-cache
 bridge-group 1
 bridge-group 1 subscriber-loop-control
 bridge-group 1 input-address-list 700
 bridge-group 1 block-unknown-source
 no bridge-group 1 source-learning
 no bridge-group 1 unicast-flooding
 bridge-group 1 spanning-disabled

As you can see it imports the address-list 700 which is all the MAC addresses for each user and Blocks - unknown-source. Do I have to edit the bridge-group or do I have to create an access-list specific for URL's and import that to the bridge-group as well? Or am I just over complicating things?

A: The control on url access does not happen there.
You should look into the configuration for a block like this:
class-map match-any nofacebook
 match protocol http host "*facebook.com"
 match protocol http host "*youtube.com"
!
policy-map nofacebook
 class nofacebook
 drop

and it would be applied to your "internet" facing interface like this:
interface GigabitEthernet0/0
 service-policy output nofacebook

Maybe your guests are being routed through another link? do you have ACLs in place?


text:
Q: Represent format of the date 2018-01-01T17:11:11.111+06:00 in string How can I represent format of 2018-01-01T17:11:11.111+06:00 in string?
I've tried yyyy-MM-dd'T'HH:mm:ss.SSS+HH:mm, but it didn't work.
It is needed for range query in elasticsearch using elastic4s.

A: Let' try:
YYYY-MM-dd'T'HH:mm:ss.SSSz

I suggest to you this app for check the format:
https://esddd.herokuapp.com/


text:
Q: JSONSimple Overwriting I am attempting to iterate through a hash map and create a json string from the values. Im using the JSONSimple library to do so.  I have the structure I want, but the values are being overwritten.  The structure I am ending up with is
{
   "new_id":{
      "coordinates_list":{
         "Coordinates: ":[
            "lat: 27.0",
            "lon: 28.0"
         ]
      },
      "t0vhf40cv86t":[
         "123"
      ]
   }
}

But there should be additional values in the JSON. Only the last row of the hash map is being included.  Do I need to add another JSONObject that I write to?
JSONObject obj = new JSONObject(); // final json object written out

    double lat = 20.00; // test data
    double lon = 21.00; // test data
    for (Map.Entry<String, List<String>> entry : data.entrySet()){
        JSONObject childObj = new JSONObject();
        JSONObject coordObj = new JSONObject();

        JSONArray entities = new JSONArray();
        JSONArray coordinates = new JSONArray();

        String key = entry.getKey();
        List<String> values = data.get(key);
        for(String value : values){
            entities.add(value);
        }
        childObj.put(key,entities);

        // increments the test data
        lat = lat +1;
        lon = lon + 1;

        coordinates.add("lat: " + lat);
        coordinates.add("lon: " + lon);

        coordObj.put("Coordinates: " ,coordinates);

        childObj.put("coordinate list ", coordObj);

        obj.put("new_id" , childObj);

    }

A: You are always using "new_id" as the key on the "obj.put" line.  For the first map entry, you set the value for that key on the JSON object.  For each subsequent entry, you are replacing the value for that key, not adding a new key.  That is why only the last entry in the map is represented in the JSON.
I'm not sure exactly what you're trying to accomplish, but you likely either need to use a different key each time through the loop or use a JSONArray instead of a JSONObject so that you don't need keys at all.


text:
Q: Netsuite Integration help I'm just starting to look into how I can make calls to Netsuite's Suitetalk API from within Salesforce. Ideally I'd like to have a panel on one of our layouts that would display a Visualforce page that calls a controller that would communicate with Suitetalk and pull back the information that I need.
I need help with making the call out to Suitetalk and parsing the response. So for example when I am viewing one of our account records in Salesforce this panel that communicates with Netsuite would display related contract info from Netsuite. Our requirements are purely read-only for now.
Can anyone point me in the right direction or provide some sample code for calling Suitetalk? I haven't been able to find much so far on how to do this through apex code.
Thanks very much in advance.

A: I've no experience with SuiteTalk so unfortunately can't help much more than pull a few bits together.
Looks like they have a WSDL http://www.netsuite.com/portal/developers/resources/suitetalk-documentation.shtml which you should be able to consume in apex to create a client stub to start out with your integration
There's some more information on using APEX generation from a WSDL here
If you've got Apex experience then you should be able to integrate using the generated classes and a custom visualforce page using the standard controller for whatever object you want your page to be on.

A: If you don't want to code it a good alternative would be lightning connect. maybe interesting to have a look at that.
http://www.odata.org/blog/netsuite-salesforce-lightning-connect/


text:
Q: Matter.js - option to add html to body I am trying out matter js to create objects (bodies) falling to gravity. Below is my sample code used to create. I want to add a hyperlink on top of this body so that user can click on created body and navigate. Is there a way to add or append HTML code to body created in Matter JS.
    var phone = Matter.Bodies.rectangle(600, 200, 65, 45,  {
        id : 'phoneBody',
    density: 30.04,
    friction: 10.01,
    frictionAir: 0.00001,
    restitution: 0.2,

    render: {
        fillStyle: '#F35e66',
        strokeStyle: 'black',
        lineWidth: 1,
        sprite: {
                    texture: './images/phone.png'
                }
    }
});
Matter.World.add(world, phone);

A: Declaring hyperlink to a body in Matter.js is a custom implementation (i.e. event handling to provide interactivity feature like hyperlinking).
This custom implementation will involve the following:

*

*Define Url for a given body

*Declare mouse event-handler for interactivity (i.e. reacting to on mouseup events)

Implementation Details
Url can be defined for a given body, as shown below:.
var phone = Matter.Bodies.rectangle(30, 50, 35, 55, {
              id : 'phoneBody',
              density: 30.04,
              friction: 0.15,
              frictionAir: 0.15,
              restitution: 0.2,
              render: {
                fillStyle: '#F35e66',
                strokeStyle: 'black',
                lineWidth: 1
              },
              url: "https://www.phone.com"
            });

Now, you need to declare mouse event-handler in-order to interact with bodies present in the world.
This is done in two stages:
  (i) Declare mouse-interactive object & add it to the world
  (ii) Declare a On-Mouseup Event-Handler to provide hyperlinking feature
// Create a Mouse-Interactive object & add it to the World
render.mouse = Matter.Mouse.create(render.canvas);
var mouseInteractivity = Matter.MouseConstraint.create(engine, {
                          mouse: render.mouse,
                          constraint: {
                            stiffness: 0.2,
                            render: { visible: false }
                          }
                         });
Matter.World.add(engine.world, mouseInteractivity);

// Create a On-Mouseup Event-Handler
Events.on(mouseInteractivity, 'mouseup', function(event) {
  var mouseConstraint = event.source;
  var bodies = engine.world.bodies;
  if (!mouseConstraint.bodyB) {
    for (i = 0; i < bodies.length; i++) {
      var body = bodies[i];
      if (Matter.Bounds.contains(body.bounds, mouseConstraint.mouse.position)) {
        var bodyUrl = body.url;
        console.log("Body.Url >> " + bodyUrl);
        // Hyperlinking feature
        if (bodyUrl != undefined) {
          window.open(bodyUrl, '_blank');
          console.log("Hyperlink was opened");
        }
        break;
      }
    }
  }
});

Feel free to play around with above implementation on CodePen >> https://codepen.io/anon/pen/xQEaQX?editors=0011

Note! In-order for the hyperlink to work, please don't forget to disable the pop-up blocker on your favourite web-browser.


text:
Q: Windows 11 installation fails My son accidentally tried to install Ubuntu 20.04.1 over a Windows 11 system. Installation has crashed with message 'creating ext4 file system'. Windows 11 boot stick can't identify any partitions, so my only other option appears to be hard disc replacement!
Using Ubuntu from a DVD (test mode) I have formatted my hard disc as NTFS, the system shows my drive as formatted with NTFS, but can't install Windows 11 and it says there is no partition!
I've tried loading diskpart, but it won't run from the Windows 'troubleshooting' command prompt.
I think I need a bootable USB stick with some way of identifying the hard disc and formatting/creating volumes/partitions so that I can install Winodws 11.
I'm not a software expert and need simple guidance!
Thanks in advance :-)

A: Thanks for all the comments. Windows 11 is not designed to allow partition changes during installation. The problem was caused by my son making a mistake that neither Windows nor Ubuntu could deal with. Even creating a new partition table and formatting correctly using Ubuntu, still prevented Windows 11 from installing. The solution was to use another PC to create a recovery disk and recover from that. It doesn't seem to matter what type of PC is used to create the recovery disk, but I suspected it would be more likely to work if I used a PC from the same manufacturer, in this case, HP.


text:
Q: Could not find SDK on kmm with AppCode I am very new to kotlin multiplatform mobile and tryed to start with AppCode and the kmm plugin. Creating and running the project on Android worked fine, but when I want to build or run the App for iOS I get the following gradle error:
Execution failed for task ':iosApp:generateIosAppEditableXcodeproj'.

> Could not find SDK.

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

I develop on a MacBook Pro M1 with macOS 12.1 and xCode 13.2.1.
How can I solve this problem?

A: Possibly related: https://youtrack.jetbrains.com/issue/KMA-355It seems like your Xcode does not have Command Line Tools installed. This can be changed by calling sudo xcode-select -s /Applications/Xcode.app/Contents/Developer or by installing them manually at the Xcode's Preferences -> Locations -> Command Line Tools.


text: Q: creating an image format with an unknown type is an error. From Image selection from photolibrary App crashes after selecting image from the simulator's photo library with the error: "[Generic] Creating an image format with an unknown type is an error"


text:
Q: Restricting access to a program in Windows Vista I need to lock down a Windows Vista Business PC. One of the requirements is that access to C:\Windows\System32\regedit.exe should be restricted to only (local) Administrators. This is a standalone PC that is not connected to ActiveDirectory or anything like that.
The default ACL permissions on this PC for regedit are:
regedit.exe D:PAI(A;;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;;0x1200a9;;;BA)(A;;0x1200a9;;;SY)(A;;0x1200a9;;;BU)S:AI

I tried changing the owner to Administrators and unchecking "Read and Execute" permission for the Users group. I figure that my user is still in the local Administrators group and they have "Read" and "Read and Execute" permissions for regedit.exe. However, when I try to open the file logged in as an admin user, I can no longer open regedit.exe, even when I right click open "Run as administrator". I get an error:

Windows cannot access the specified
  device, path, or file. You may not
  have the appropriate permissions to
  access the item.

What am I misunderstanding about Windows Vista file access? What settings will allow a user in the Administrators group to open regedit.exe but no other users?

A: Well... unless you lock down the whole machine, anything like this will simply not work.
There are hundreds of third party tools out there that allow registry editing.
If however you just want the basic disable access to regedit protection, open Registry Editor and navigate to HKEY_CURRENT_USER \ Software \ Microsoft \ CurrentVersion \ Policies and create a Dword with name DisableRegistryTools and value of 1.
And done!

A: Unfortunately, you cannot do this for the whole registry itself, but put all the users you do not want to have access into a new group, then give that group the "deny" permission to that regedit.exe program, and anything else you don't want them to touch. Deny will overrule any other permissions you have previously set. You may restrict them too much it you do it on certain folders, and "break" some programs, so test it if you do that.
Since it will inherit the permissions, you will need to go to advanced and uncheck that, then when prompted, click copy. This copies the inherited permissions, but makes them originate there.
As pointed out, this will not stop a knowledgeable user, but will stop most.
If you really need to lock down a computer for a specific user, I recommend this program (It is pretty amazing really):
http://www.fortresgrand.com/products/f101/f101.htm


text:
Q: cant extract date '/Date(1617667200000+0000)/' I am using cakephp4 and a Xero API. I can't find the code to convert a date returned as '/Date(1617667200000+0000)/' from a Xero API. It is a timestamp with the first 10 digits eg the $rr=gmdate("Y-m-d", 1617667200); will work but I can't hardcode strings like this or just find the first 10 digits. It's a StringUtil I believe. I tried using JSON date examples as well but not getting anywhere including Xero docs.
 $rr=StringUtil::convertStringToDate($date);//no
 $rr=gmdate("Y-m-d", $date);  //no

Converting json results to a date

A: A regular expression will extract this with ease:
$text = '/Date(1617667200000+0000)/';
preg_match('#^/Date\((\d{10})#', $text, $matches);  // Use # as delimiter.
                                                    // From start match /Date(
                                                    // match and capture next 10 digits

$dt = new DateTime('@'.$matches[1]);                // Create PHP DateTime object from unix timestamp

echo $dt->format('Y-m-d H:i:s');    // 2021-04-06 00:00:00

See https://3v4l.org/5jT5B
Edit - simpler version, no need for a regex if the data format is consistent
$text = '/Date(1617667200000+0000)/';
$timeStamp = substr($text, 6,10);
$dt = new DateTime('@'.$timeStamp);                // Create PHP DateTime object from unix timestamp

echo $dt->format('Y-m-d H:i:s');    // 2021-04-06 00:00:00


text:
Q: ORDER BY Clause in FOR XML EXPLICIT I have a rather large query (25 tags across a dozen tables; ~1500 lines) that needs to be formatted into XML using FOR XML EXPLICIT. Unfortunately, the consumer of this file has demanded the use of CDATA tags, otherwise I would be using FOR XML PATH.
This is what I'm looking for:
<elem elem_att1="..." elem_att2="1" elem_att3="...">
    ...
    ...
    <c>...</c>
    <d>...</d>
    <e>
        <e1 e1_att1="..." e1_att2="1">
            <e11>...</e11>
            <e12><![CDATA[...]]></e12>
            <e13><![CDATA[...]]></e13>
        </e1>
        <e1 e1_att1="..." e1_att2="2">
            <e11>...</e11>
            <e12><![CDATA[...]]></e12>
            <e13><![CDATA[...]]></e13>
        </e1>
        <e1 e1_att1="..." e1_att2="3">
            <e11>...</e11>
            <e12><![CDATA[...]]></e12>
            <e13><![CDATA[...]]></e13>
        </e1>
    </e>
    <f>
        <f1 f1_att1="..." f1_att2="..." />
        <f2 f2_att1="..." f2_att2="..." />
        <f3 f3_att1="..." f3_att2="..." />
    </f>
</elem>

Assume that the following tag and parent mappings have been properly defined in in the query:
      Tag | Parent
elem  2   | 1
a     3   | 2
b     4   | 2
c     5   | 2
d     6   | 2
e     7   | 2
e1    8   | 7
e11   9   | 8
e12   10  | 8
e13   11  | 8
f     12  | 2
f1    13  | 12
f2    14  | 12
f3    15  | 12

I've gotten about 90% of the way there with the query but am encountering an issue related to order of tags within the universal table. I would expect to see the following output for the first two columns of the table returned from the query:
Tag | Parent
2   | 1
3   | 2
4   | 2
5   | 2
6   | 2
7   | 2 <-- beginning of the "e" element
8   | 7 <-- first instance of the "e1" element
9   | 8
10  | 8
11  | 8
8   | 7 <-- second instance of the "e1" element
9   | 8
10  | 8
11  | 8
8   | 7 <-- third and final instance of the "e1" element
9   | 8
10  | 8
11  | 8
12  | 2 <-- beginning of the "f" element
13  | 12
14  | 12
15  | 12

Instead, I'm getting this as the first two columns of the query output:
Tag | Parent
2   | 1
3   | 2
4   | 2
5   | 2
6   | 2
7   | 2 <-- beginning of the "e" element
12  | 2 <-- beginning of the "f" element
13  | 12
14  | 12
15  | 12
8   | 7 <--first instance of the "e1" element
9   | 8
10  | 8
11  | 8
8   | 7 <-- second instance of the "e1" element
9   | 8
10  | 8
11  | 8
8   | 7 <-- third and final instance of the "e1" element
9   | 8
10  | 8
11  | 8

Which would obviously generate malformed XML along the lines of this:
<elem elem_att1="..." elem_att2="1" elem_att3="...">
    ...
    ...
    <c>...</c>
    <d>...</d>
    <e />
    <f>
        <f1 f1_att1="..." f1_att2="..." />
        <f2 f2_att1="..." f2_att2="..." />
        <f3 f3_att1="..." f3_att2="..." />
    </f>
        <e1 e1_att1="..." e1_att2="1">
            <e11>...</e11>
            <e12><![CDATA[...]]></e12>
            <e13><![CDATA[...]]></e13>
        </e1>
        <e1 e1_att1="..." e1_att2="2">
            <e11>...</e11>
            <e12><![CDATA[...]]></e12>
            <e13><![CDATA[...]]></e13>
        </e1>
        <e1 e1_att1="..." e1_att2="3">
            <e11>...</e11>
            <e12><![CDATA[...]]></e12>
            <e13><![CDATA[...]]></e13>
        </e1>
    </e>
</elem>

The query chokes and throws the following error:
Msg 6833, Level 16, State 1, Line 2
Parent tag ID 7 is not among the open tags. FOR XML EXPLICIT requires parent tags to be opened first. Check the ordering of the result set.

Here is my order by clause:
order by [elem!2!att2], [e1!8!att2]

If I change the order by clause to
order by [elem!2!att2], tag, [e1!8!att2]

the query executes successfully, but all child records of e1 elements are nested under the last e1 element:
<elem elem_att1="..." elem_att2="1" elem_att3="...">
    ...
    ...
    <c>...</c>
    <d>...</d>
    <e>
        <e1 e1_att1="..." e1_att2="1" />
        <e1 e1_att1="..." e1_att2="2" />
        <e1 e1_att1="..." e1_att2="3">
            <e11>...</e11>
            <e11>...</e11>
            <e11>...</e11>
            <e12><![CDATA[...]]></e12>
            <e12><![CDATA[...]]></e12>
            <e12><![CDATA[...]]></e12>
            <e13><![CDATA[...]]></e13>
            <e13><![CDATA[...]]></e13>
            <e13><![CDATA[...]]></e13>
        </e1>
    </e>
    <f>
        <f1 f1_att1="..." f1_att2="..." />
        <f2 f2_att1="..." f2_att2="..." />
        <f3 f3_att1="..." f3_att2="..." />
    </f>
</elem>

The actual question:
What is causing f and its children to populate in the result set prior to the population of e's children?
I'm hoping this is a relatively common mistake, the solution to which is abstract enough to be relayed without having to copy over 1500 lines of code.

A: Long time since I've used this but have you tried
order by [elem!2!att2], [e], [e1!8!att2]

or
order by [elem!2!att2], 7, [e1!8!att2]


text:
Q: Java Scanner ListArray ParseInt Попробовал справиться с закрытием потока System.in через строковые методы. Получил исключение Ввод:
-574 -484 444 -217 978 -370 269 -9 189
Scanner input = new Scanner(System.in);
String sc = input.nextLine();
String[] numbers = sc.split(" ");
input.close();
List result = new ArrayList<>();
for (int x = 0; x < numbers.length; x++) {
    String item = numbers[x];
    if (result.contains(item)) {
        continue;
    }
    result.add(item);
}
int[] vals = new int[result.size()];
for(int x = 0; x<result.size(); x++) {
    vals[x] = Integer.parseInt(result.get(x));
}
System.out.println(vals);

Результат меня удивил ... ( ожидал, что заберёт строку, распарсит в целые и выдаст в массиве ...  -574 -484 444 -217 978 -370 269 -9 189
[I@37bba400

A: Вопрос очень неясен, нужно детально описывать проблему и прикладывать ошибку. Попробую раскрыть из того что видно.

*

*List result = new ArrayList<>(); - это нетипизированный (raw-тип) список, поэтому result.get() вернёт Object, поэтому компилятор выдаст ошибку на Integer.parseInt(result.get(x)). Наилучший вариант здесь - сделать типизацию:
List<String> result = new ArrayList<>();

*System.out.println(vals) выдаёт дефолтное строковое представление массива. Дефолтным строковым представлением массива является вот эта слабочитаемая абракадабра [I@37bba400, которая обозначает что это массив целых с хешем равным 0x37bba400; Для нормального представления в строке стоило бы использовать утилитный метод Arrays.toString: System.out.println(Arrays.toString(vals));

*Это не ошибка, но я бы советовал вместо явного закрытия стрима вызовом close(), использовать try-with-resources.
Итого, после всех правок, код должен выглядеть как-то так:

        try (Scanner input = new Scanner(System.in)) {
            String sc = input.nextLine();
            String[] numbers = sc.split(" ");

            List<String> result = new ArrayList<>();
            for (int x = 0; x < numbers.length; x++) {
                String item = numbers[x];
                if (result.contains(item)) {
                    continue;
                }
                result.add(item);
            }
            int[] vals = new int[result.size()];
            for (int x = 0; x < result.size(); x++) {
                vals[x] = Integer.parseInt(result.get(x));
            }
            System.out.println(Arrays.toString(vals));
        }

Для введённой строки -574 -484 444 -217 978 -370 269 -9 189 вывод будет следующий:
[-574, -484, 444, -217, 978, -370, 269, -9, 189]


text:
Q: For CSS background-image character face got cut off once the screen getting bigger https://codepen.io/demi-chen/pen/vYLPQyv
For CSS  background-image character face got cut off once the screen getting bigger how to make sure the screen at least shows the complete face. I have tried to adjust background-position but it seems not working. Thanks
for the background-image parts

.hero {
  background-image: url(https://upload.cc/i1/2020/08/16/BZimrY.jpg);
  background-repeat: no-repeat;
  background-size:cover ;
  color:#fff;
  padding: 4em 0;
  background-position: bottom;
}

A: You can directly specify a max-width after which it should stop expanding since the face in the image is going out. So it can be done as -

const closeNav =  document.querySelector(".close-nav")
const getNav= document.querySelector(".nav")
const openNav = document.querySelector(".closetag")

closeNav.addEventListener ("click", function() {
    getNav.classList.remove('navigation-open');
});

 openNav.addEventListener("click",function(){
   getNav.classList.add('navigation-open')
 })
* {box-sizing: border-box;}

body {
  margin:0;
  font-family: 'Montserrat',sans-serif;
  font-size:1rem;
  color:#404040;
  line-height:1.6
}

h1, h2, strong {
  font-weight: 700;
}

.hero {
  background-image: url(https://upload.cc/i1/2020/08/16/BZimrY.jpg);
  background-repeat: no-repeat;
  background-size:cover ;
  color:#fff;
  max-width: 1250px;
  margin: auto;
  padding: 4em 0;
  background-position: bottom;
}

.accent-color {
  color:#ffe600
}

.hero-title {
  font-size:1.5rem;
  line-height:1.4;
  margin-bottom:0;
  margin-top: 5rem;
}

.hero > * {
  grid-column:2/-2
}

@media (min-width:600px) {
  .hero > * {
  grid-column:2/ span 2
}

}
.btn-primary {
  background-color: #ffe600;
  color:black;
  text-decoration:none;
  justify-self:start;
  align-self: center;
}

.btn {
  padding:0.5em 1.5em;
  margin-top:0.5em;
  font-weight:700;
}

/* =================
    general layout
====================*/
.main-grid {
  display: grid;
  grid-template-columns: minmax(1em,1fr) minmax(0px,500px) minmax(1em,1fr);
   grid-gap: 0em 2em
}

@media (min-width: 600px){
  .main-grid {
    grid-template-columns: minmax(1em,1fr) repeat(3,minmax(130px,320px)) minmax(1em,1fr)

  }

}
/* =================
   info section
==================*/

.info >* {
  grid-column:2/-2
}

.info {
  padding: 4em 0;
}

.info > h3 {
  text-align:center
}

@media (min-width: 600px) {
  .col {
    grid-column: span 1;
    }
  .col:first-child {
    grid-column:2/3
  }
}

/* =================
   footer section
==================*/

.footer >* {
  grid-column:2/-2
}

.social-item {
  list-style-type: none;
}

.footer {
  background-color: #ebebeb;
  text-align:center;
  padding: 1.5em;
}

ul.social-list {
    order:-1;
    padding:0;
    margin:0;
    display:flex;
    justify-content: center;
    letter-spacing:1em;
    font-size:1.5rem;
}

.social-link {
  color:black;
}

.social-link:hover,
.social-focuse{
  color: #777
}

.fa-facebook-square {
  margin-left:20px
}

.footer-main > * {
  opacity: 0.6
}

@media (min-width: 600px) {
  .footer-main {
     grid-column: 1 / 4;
     text-align:start;
     margin-left: 2em;
    }

  .social-list{
    grid-column:  4 / 6 ;
    grid-row: 1 / 3 ;
    justify-self: end;
    align-self: center;
  }
}

.logo-link {
  background-color: yellow;
  padding-top: 2em;
}

.nav-list {
   display: flex;
   flex-direction: column;
   justify-content: space-around;
   align-items: center;
   list-style: none;
   margin: 0;
   padding: 0;
   height: 100%;
}

.nav-link {
  color:white;
  text-decoration:none;
  font-size: 2rem;
  font-weight:700;
  letter-spacing:1px;
}

.header-content {
    display: flex;
    grid-column: 2/-2;
}

header.main-grid {
    position: absolute;
    width: 100vw;
}
.nav {
  position:fixed;
  background-color: #000;
  width: 100%;
  top: 0;
  right: 0;
  left: 0;
  bottom 0;
  height: 100%;
  left: 100%;
  transform: translateX(0%);
  transition: 0.5s
}

.navigation-open {
    transform: translateX(-100%);
}

.nav-link:hover,
.nav-link:focus {
  color: yellow
}

.close-nav {
  background-color: #000;
  border:0;
  color:yellow;
  font-size:3rem;
  cursor:pointer;
  padding: .5em;
  position: absolute;
}

.fas {
  font-size:2.5em;
  color:white;
}

.closetag {
  position: absolute;
  right:1%;
  top:20%;
  background-color: #000;
  border:0;
  cursor: pointer;
  padding: .3em 1.5em;
  background-color: TRANSPARENT;
}

.close-nav:hover {
  color: white
}
.close-nav:focus,
.closetag:focus {
  outline: none;

}

.fas:hover {
  color:yellow
}

@media (min-width:600px) {
  button.closetag,
  .close-nav {
    display: none;
}
  .nav {
    background-color: transparent;
    position: initial;

    }
  .nav-list {
    flex-direction: row;
    justify-content: unset;
  }

  .nav-link {
    font-size:1.4rem;
    margin-left: 18px;
  }

  .header-content {
    align-items: center;
  }

}

   <button class="closetag"></button>

      <button aria-label= "Close navigation" class="close-nav">×</button>

home

about us

contact

The only marketing agency on  a mission from God , fully dedicated to increase your web traffic.

We're two brothers from Chicago that are trying to pay back our debt. We can help you with SEO, SEM, content marketing and whatever else.

       contact us

About Us

We grew up in downtown Chicago, and we used to play in a band. Jake loves fried chicken, and Elwood loves dry white toast.

Our skills

Elwood is an expert in SEO, SEM, and driving from the police. Jake is our social media specialist, and he has an amazing voice.

Get in touch

Send us an email with some info about what help you need and we'll drive over to your place in our Bluesmobile the following day to discuss the deal.

Jake&Elwood

Two brothers from Chicago that are just trying to pay back their debt by helping others with their SEO, SEM, and Content Marketing needs.

© Jake&Elwood 2019

The max-width will ensure the image face doesn't go outside image and margin:auto; will make sure that the image stays in the middle.


text:
Q: DateTime.parseExact no funciona Quiero validar si un string es una fecha, el string lo traigo de una conexión con una API y viene de la siguiente manera
20181025
public static Boolean IsDate(string Expression)
    {
        Boolean resultado = false;
        try
        {
            DateTime isDate = DateTime.ParseExact(Expression, "dd/MM/yyyy", null);
            resultado = true;
        }
        catch
        {
            resultado = false;
        }
        return resultado;
    }

pero aun usando el DateTime no logro parsearlo y la funcion me devuelve false

A: El formato que tratas de de introducir para el valor 20181025 es "yyyyMMdd", pero estas definiendo usar el formato  "dd/MM/yyyy", lo cual es incorrecto:
  DateTime isDate = DateTime.ParseExact(Expression, "dd/MM/yyyy", null);

si deseas usar el formato "yyyyMMdd", debes definirlo para el método DateTime.ParseExact() :
  DateTime isDate = DateTime.ParseExact(Expression, "yyyyMMdd", null);

A: La fecha es 20181025 no coincide con el formato que estás indicando en DateTime.ParseExact, en lugar de "dd/MM/yyyy" prueba con "yyyyMMdd".


text:
Q: How to send keys to Ionic 4 input with Appium? I am using Ionic 4 (beta) and am unsure what the best (/easiest) way is to send keys to an input field using Appium.
Ionic HTML code:
<form>
    <ion-item>
        <ion-label position="floating">E-mail</ion-label>
        <ion-input [formControl]="email" id="sign-in-email-input" type="email" autofocus="true"></ion-input>
    </ion-item>
</form>

In my appium test I want to send keys to this input. I notice in Chrome dev tools that below the ion-input a native input is created by Ionic, which is in a shadow dom. So -after some googling- I go after it like this:
email = driver.find_element_by_id('sign-in-email-input')
jsCommand = "return arguments[0].shadowRoot.querySelector('input');"
emailNative = driver.execute_script(jsCommand, email)
emailNative.send_keys('test@test.com')

But the send_keys command throws "StaleElementReferenceException: Message: Element is no longer attached to the DOM".
I'm going around this by doing:
email = driver.find_element_by_id('sign-in-email-input')
jsCommand = "arguments[0].shadowRoot.querySelector('input').value = 'test@test.com';"
driver.execute_script(jsCommand, email)

That seems to work at first (I see the value appear in the IOS simulator). But when focus moves to another field, the value disappears.
What is the correct way to send keys with Appium to an input in Ionic 4?


text:
Q: Handel http requests between 2 servers i have a website hosted in 2 different servers , i want to avoid losing traffic when one server of them go down , is there any way to balance the redirect between these 2 servers in the register side (namecheap) , so if the primary server went down the request will be redirected automatically to the other server.
Thank you


text:
Q: Magento 2 Docker: Frontend ignore updated files i'm losing my mind and work.
This is not my first Docker expierience, I worked with magento-docker in the past.
Today I have this strange problem that cannot resolve by myself and seem no other had.
When I save a file  on vendor or app/design folder Magento completely ignore the update.
I am sure that this files in the container (bin/magento-docker bash) are up to date immediately on save. It seems like the web server don't take this files.
bin/magento cache:clean/flush do not resolve, I had to stop and restart docker
The containers are create with ece-tools build:compose with --no-varnish option


text:
Q: Simple.Data framework: join doesn't work I'm trying to do a simple join with Simple.Data but I can't get it working. I'm sure that I'm missing something but I don't get it...
SQL:
CREATE TABLE TestA
(
    ID INTEGER PRIMARY KEY,
    Txt TEXT
);

CREATE TABLE TestB
(
    ID INTEGER PRIMARY KEY,
    Aref INTEGER,
    Txt TEXT,

    FOREIGN KEY(Aref) REFERENCES TestA(ID)
);

INSERT INTO TestA
VALUES (1, 'This is Test A!');

INSERT INTO TestB
VALUES (1, 1, 'This is TestB!');

C#:
db.TestB.Find(db.TestB.Aref = db.TestA.ID);

If I run the code I'll get a RuntimeBinderException: 'Simple.Data.ObjectReference' does not contain a definition for 'Aref'.
I'm using Simple.Data.Core/Ado v0.12.2.2 and Simple.Data.Sqlite v0.12.2.4
I already checked the Docs but I can't see my mistake. What I am doing wrong?
Edit:
I also tried the index style:
db["TestB"].Find(db["TestB"]["TestA"]["ID"] == db["TestB"]["Aref"]);

The generated SQL looks like this:
select [TestB].* from [TestB]  JOIN [TestA] ON ([TestA].[Aref] = [TestB].[ID]) where [TestA].[ID] = [TestB].[Aref]

It seems like that the tables in the ON part are inverted, actually it should be like the WHERE part ...

A: Try this:
using(var db = new MyEntities())
{
    var sql = db.TestB.Include("TestA");
    var data = sql.ToList();

    //the var data will now contain the queried data.
    //you could bind the var to a datagrid.

    //WPF datagrid
    MydataGrid.DataContext = data;

    //Asp.net datagrid
    MyDatagrid.DataSource = data;
    MyDatagrid.DataBind();

    //Or loop thru the results
    foreach(var item in data)
    {
         MessageBox.Show("Column -> " + item.ColumnName);
    }

}

A:       List<TestB> source = db.TestB.FindAll()
            .Select(db.TestB.ID,
            db.TestB.Aref,
            db.TestB.Txt,
            db.TestB.TestA.ID,
            db.TestB.TestA.Txt)
            .Join(db.TestA).On(db.TestA.ID == db.TestB.Aref);

This example get all record from table TestB. You can select what column you want get in section select.
I hope this help you.


text:
Q: Coverity Scan fails to build  with _GNU_SOURCE defined The Coverity Scan Build Tool fails to compile any C file that includes <stdlib.h> on Ubuntu 18.04 when _GNU_SOURCE is defined:
$ cat > main.c
#include <stdlib.h>
int main() {
}
$
$ gcc -D_GNU_SOURCE=1 -o main main.c
$
$ /opt/cov-analysis/bin/cov-build --dir cov-int gcc -D_GNU_SOURCE=1 -o main main.c
Coverity Build Capture (64-bit) version 2017.07 on Linux 4.15.0-20-generic x86_64
...
[WARNING] Emitted 0 C/C++ compilation units (0%) successfully
...
$

The same build works perfectly on Ubuntu 16.04 or without _GNU_SOURCE defined:
$ /volatile/local/cov-analysis/bin/cov-build --dir cov-int gcc -o main main.c
Coverity Build Capture (64-bit) version 2017.07 on Linux 4.15.0-20-generic x86_64
...
Emitted 1 C/C++ compilation units (100%) successfully
...
$

How to get Coverity Scan to build C sources with _GNU_SOURCEdefined on Ubuntu 18.04?
For those interested file cov-int/build-log.txt can be found here:
https://gist.github.com/DimitriPapadopoulos/0dcd9018eed26401cc6095087d9cc1d5

A: After contacting Coverity support, it appears this is known bug. They suggested I work around it by switching from the default Ubuntu 18.04 compiler (GCC 7) to the previous version (GCC 6):
sudo apt install gcc-6

Indeed _Float32, _Float32x, _Float64, _Float64x and _Float128 were introduced in GCC 7.

A: Coverity is failing to define the types GCC would define, but then it's claiming to be GCC anyway.  Here's a workaround: https://gist.github.com/vathpela/0cede6d6eb5b0ec0791c6afc4282c340#file-fix_coverity-h
Just be sure you do:
#include "fix_coverity.h"

before stdlib.h gets included, whether directly or indirectly.


text:
Q: Grow two Ubuntu partitions using unallocated space before them I want to merge the unallocated space with my Ubuntu partitions. I want to add 80GB more to sda7 partition and allocate the remaining space to the sda8 partition. How can I do this with GParted?
Below is a screenshot of the disk structure.

A: *

*Boot from the installation media a select "Try Ubuntu".

*Run GParted.

*Using GParted:

*

*Move your /dev/sda7 partition to the left (either as far as possible, or leave some space for possible future expansion of the Windows partition /dev/sda3), and resize it according to the plan.

*Then move /dev/sda8 as far to the left as possible, and resize it to the maximum possible.


text:
Q: Docker compose: nginx with self SSL cert not working I'm trying to create a development enviroment using nginx, mysql and php. I want to have a self signed SSL certificate configured because in productions I'll use ssl connections as well.
For php and mysql I had no problems, but for nginx and struggling to make it work. I'm using MarvAmBass/docker-nginx-ssl-secure image (https://github.com/MarvAmBass/docker-nginx-ssl-secure) but when accessing the site I get the SEC_ERROR_UNKNOWN_ISSUER error in Firefox (invalid ssl certificate).
I've replaced the CN var in the command to create the self certificate but doesn't seem to affect.
I don't know if maybe there's another image I can use (I'm pretty new to the docker world).
Thanks in advance

A: If the certificate is not authorized by the valid CA(Certificate Authority), then you will notice SEC_ERROR_UNKNOWN_ISSUER on Mozilla. It is recommended to use the certificates provided by your CA(Certificate Authority).


text:
Q: Why doesn't my string comparison with == work? I have this, in my onPostExecute :
    String test = currentActivity.getClass().getSimpleName();
    if(test == "SplashScreen"){
        Log.e("OK",test);

    } else {
        Log.e("OK",test);

    }

The problem is, the value of test is "SplashScreen" (that we can see with the log), but the code never goes in the if, only in the else.
Why does this happen?

A: As the others had already said you can not use the == operator on strings.
The reason for this is that strings are objects and not primitive datatypes.
With that said the == operator will check if the two strings has the same memory point in the memory if I'm not mistaken.

A: use equals to compare strings:
 if(test.equals("SplashScreen"){
  Log.e("OK",test);

 } else {
    Log.e("OK",test);

}

A: You can't use == on strings. You should use:
"SplashScreen".equals(test)

Test might be null, it is better to call equals() on "SplashScreen" since you know that it is no null.

A: Don't compare string with == use .equals()
String test = currentActivity.getClass().getSimpleName();
if(test.equals("SplashScreen")){
    Log.e("OK",test);

} else {
    Log.e("OK",test);

}

A: It's better to use equalsIgnoreCase(String string).
 String test = currentActivity.getClass().getSimpleName();
if(test.equalsIgnoreCase("SplashScreen")){
    Log.e("OK",test);

} else {
    Log.e("OK",test);

}


text:
Q: Using Casbah in Scala/Scalatra to query for a document I am slightly confused on how to retrieve an individual document from MongoDB using Casbah in my Scalatra project. Currently, I have some code that hypothetically looks like the following:
get ("/dogs") {
    val collar_id = params.getOrElse("collar_id", 1)
    val mongoColl = mongoDb("pets")("dogs")
    val o: DBObject = MongoDBObject("collar_id" -> collar_id)
    val b = mongoColl.findOne(o)

    b.json_document
}

In this case, the document b has a json_document field that has all of the data I need to get rendered in the response as JSON. The problem is, I don't seem to be querying MongoDB properly here using Casbah. The equivalent of how I'd query this using mongodb's client would be:
db.dogs.findOne({collar_id: 5})
What's the correct way to write my query code above to get similar results? Passing in collar_id as a string or Int doesn't seem to work. Also get an error on returning b.json_document:
 value json_document is not a member of Option[mongoColl.T]

A: Are params a map of ints or strings? If the var collar_id is a string, but you store it as an int when you query it wont find any results.
Here's an example of ensuring collar_id is a valid int based on params of Map[string, Any]:
val collar_id = params.getOrElse("collar_id", "1").toString match {
    case x if x.forall(Character.isDigit) => x.toInt
    case _ => 1
}

A: You can use the getAs method on the params value:
get("/api/dogs/:collarId") {

  val query = for {
    collarId <- params.getAs[Long]("collarId")
    collar <- mongoColl.findOne(MongoDBObject("collar_id" -> collarId))
  } yield collar

  query match {
    case Some(x) => x
    case None => halt(404)
  }

}

This works also great with scalaz's \/ type:
get("/api/dogs/:collarId") {

  for {
    collarId <- params.getAs[Long]("collarId") \/> BadRequest()
    collar <- mongoColl.findOne(MongoDBObject("collar_id" -> collarId)) \/> NotFound()
  } yield collar

}


text:
Q: Django - Why user did not pass IsAdminUser, but django does not throw exception of unauth? Here is my sample code of using Token Authen:
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from django.http.response import HttpResponse
class test_api(generics.GenericAPIView):
    permission_classes = (IsAdminUser, IsAuthenticated)
    def get(self,request):
        return HttpResponse("You call random test api")

I am using Token Authen, with my header of request like this, this is a Token of NOT AdminUser
 Authorization : Token fc823d7a1d8973056e11e9c8b974f17e351c4263

When I call the api, It print out of terminal these lines
False
[23/Aug/2021 10:39:20] "GET /user/get-user HTTP/1.1" 200 13

I suppose the False got print out from IsAdminUser permission. However, the code still reponse 200 and give me response of You call random test api.
Only when I give the wrong Token, I receive 403 Unauth response.
FYI my user model:
class UserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError("User must have an email address")
        user = self.model(email=self.normalize_email(email),  **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    def create_superuser(self, email, password):
        """Creata and saves a new super user"""
        user = self.create_user(email,password)
        user.is_staff = False
        user.is_superuser = True
        user.save(using= self._db)
        return user

class User(AbstractBaseUser, PermissionsMixin):
    """Custom user model that support using email instead of username"""
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_employee = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'

A: As documented:

The IsAdminUser permission class will deny permission to any user, unless user.is_staff is True in which case permission will be allowed.

Thus, it seems that the user for the token has is_staff set to True. You can confirm this by adding the following lines in your get()
def get(self, request):
    print("request.user.is_staff", request.user.is_staff)
    return HttpResponse("You call random test api")


text:
Q: Migrating from Selenium RC to Webdriver I'm trying to migrate to webdriver, as it is faster. How do I do this?
Currently I'm using the setUp() command for selenium. Do I need to add any new jar files for the webdriver?

A: I 'd like to describe in common features approach I use on my project.
I'm using selenium webDriver. Working on java.
IDE: IDEA.
build manager: maven.
So I got POM.xml file.
So I simply add there depencdencies in POM xml:
<dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.4</version>
      </dependency>

      <dependency> <groupId>org.seleniumhq.selenium</groupId>
          <artifactId>selenium-java</artifactId>
          <version>2.24.1</version>
      </dependency>

On building the project maven will get needed jars automatically.
In my project I got BaseSeleniumTest.java: with the following:
public class BaseSeleniumTest extends SeleneseTestBase {
    static WebDriver driver;

    @BeforeClass
    public static void firefoxSetUp() throws MalformedURLException {

        driver = new FirefoxDriver();
    }
    @Before
    public void homePageRefresh() throws IOException {
        driver.get("login.base.url");
    }

    @AfterClass
    public static void closeFirefox(){
        driver.quit();
    }
...
}

And have some other classes inherinting from BaseSekeniumTest.java
where I describe pack of my selenium tests annotated by @Test
That's kind of structure on my project.
Hope this helps you.


text:
Q: Uniform continuity of composition? If we consider $f\circ u$ and know that

*

*f is bounded and uniformly continuous

*u is bounded and continuous

does this imply that $f\circ u$ is bounded and uniformly continuous?
It is clear that it is bounded.
But it is not clear to me whether it is uniformly continuous. Surely it is continuous.

A: The answer is no. You can give the following counter-example. Let your domain be $(0,1)$, $f(x)= x$ and $g(x)= x^2$. Then $f(g(x))= f(x^2)= x^2$ which is bounded, continuous, but not uniformly continuous on the given domain.


text:
Q: How to put text in input line: how to ask for user input on the command line while providing a 'default' answer that the user can edit or delete? I am creating a Python script that asks for input from the command line. The user will have the ability to edit a part of a file. I can ask for the new information and overwrite it in the file, no problem. But I would rather have the to-edit part of the file already put in the command line, so it does not have to be typed completely over. Is this possible?
File:
1|This file
2|is not empty

Example:
>>>edit line 2
Fetching line 2
Edit the line then hit enter
>>>is not empty                  #This is written here by the script, not by the user

Which then can be changed to
>>>is not full either
Edited file

Afther which the file has changed to:
1|This file
2|is not full either

I hope it's clear what I am trying to accomplish.
This question has been said to answer my question, it does to a certain extent. It does when I am running Linux with readline. However, I am not. I am using Windows and am not using readline. I would like to only use the standard library.
An answer for Windows is also provided with that question. However, I get an  ImportError with win32console, it might be because mentioned question is not about Python3.4, but mine is.
Also, I was wondering if this was possible with the standard library, not with an external library.

A: Unfortunately, I don't know if kind of input() with default value is available in standard library.
There is an external solution - use win32console as mentioned in this answer. However, it has two pitfalls as far as I can see. First, the import is bundled in a package pywin32. So you would use pip install pywin32, except it does not work, because of the second pitfall: the information about the package at pypi is outdated, it says that package is incompatible with Python 3.4...
But in fact, it can work! You should follow the "Download URL" visible at pypi project page (i.e. https://sourceforge.net/projects/pywin32/files/pywin32/ ) and install latest build. I just installed build 219 for Py3.4, as I myself also use this Python version. On the page installers are provided for several Python versions for 32bit and 64bit Windows.
Also, I've tweaked the code from above-linked SO answer to work in Python 3:
import win32console

_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)

def input_def(prompt, default=''):
    keys = []
    for c in str(default):
        evt = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
        evt.Char = c
        evt.RepeatCount = 1
        evt.KeyDown = True
        keys.append(evt)

    _stdin.WriteConsoleInput(keys)
    return input(prompt)

if __name__ == '__main__':
    name = input_def('Folder name: ', 'it works!!!')
    print()
    print(name)

This works on my Windows machine... If this does not work on yours, can you provide the error message?

A: I have written a line editor which hopefully does what you are looking for. But it is a quick-and-dirty hack. It is Windows only and written with CPython 3.6.5 on Windows 10, so its use might be limited. It has been tested on codepage 1252 (ANSI Latin 1; Western European (Windows)) and codepage 65001 (utf-8). It is very basic and a bit sluggish as it is not speed-optimized. (I should rewrite it in C but I do not have the time.) It is hardly tested and poorly documented.
import msvcrt
import os
import sys

if os.name != 'nt':
    raise NotImplementedError('This module works only on MS Windows!')

CTRL_00         = 0
CTRL_E0         = 224
KEY_BACKSPACE   = 8
KEY_DELETE      = 83                                            # CTRL
KEY_END         = 79                                            # CTRL
KEY_ESC         = 27
KEY_HOME        = 71                                            # CTRL
KEY_INSERT      = 82                                            # CTRL
KEY_LEFT        = 75                                            # CTRL
KEY_RETURN      = 13
KEY_RIGHT       = 77                                            # CTRL

flush = sys.stdout.flush
write = sys.stdout.write

mode    = ('[OVR]> ', '[INS]> ')                                # overwrite, insert
prefix  = len(mode[0])

def _update_line(insert, source, length, line, target):
    """Write a new line and position the cursor.
    source: previous cursor position
    length: old line length
    line:   edited line
    target: next cursor position
    """
    write('\b' * source)                                        # set cursor to start of line
    write(' ' * length)                                         # erase old line
    write('\b' * length)                                        # again, set cursor to start of line
    write(mode[insert] + line[prefix:])                         # write updated line
    write('\b' * (len(line) - target))                          # set cursor to new position
    flush()                                                     # write buffer to screen

def mswin_line_edit(default_string, insert=True):
    """Edit a MS Windows CLI line."""

    insert = insert
    line = mode[insert] + default_string
    count = len(line)
    before = line[:count]
    after = line[count:]
    print(line, end='', flush=True)
    cursor = count

    while True:
        key = msvcrt.getwch()
        num = ord(key)
        if num == KEY_ESC:                                      # abort edit
            return default_string
        if num == KEY_RETURN:                                   # finish edit
            return line
        if num == KEY_BACKSPACE:                                # delete character before cursor
            if cursor > prefix:
                before = line[:cursor - 1]
                after = line[cursor:]
                line = before + after
                _update_line(insert, cursor, count, line, cursor - 1)
                cursor -= 1
                count = len(line)
        elif num == CTRL_E0 or num == CTRL_00:                  # CTRL
            ctrl = ord(msvcrt.getwch())
            if ctrl == KEY_END:                                     # set cursor after last character
                if cursor < count:
                    before = line
                    after = ''
                    _update_line(insert, cursor, count, line, count)
                    cursor = count
            elif ctrl == KEY_HOME:                                  # set cursor before first character
                if cursor > prefix:
                    before = ''
                    after = line
                    _update_line(insert, cursor, count, line, prefix)
                    cursor = prefix
            elif ctrl == KEY_LEFT:                                  # move cursor 1 character to the left
                if cursor > prefix:
                    before = line[:cursor]
                    after = line[cursor:]
                    _update_line(insert, cursor, count, line, cursor - 1)
                    cursor -= 1
            elif ctrl == KEY_RIGHT:                                 # move cursor 1 character to the right
                if cursor < count:
                    before = line[:cursor]
                    after = line[cursor:]
                    _update_line(insert, cursor, count, line, cursor + 1)
                    cursor += 1
            elif ctrl == KEY_DELETE:                                # delete character after cursor
                if cursor < count:
                    before = line[:cursor]
                    after = line[cursor + 1:]
                    line = before + after
                    _update_line(insert, cursor, count, line, cursor)
                    count = len(line)
            elif ctrl == KEY_INSERT:                                # switch insert/overwrite mode
                insert ^= True
                _update_line(insert, cursor, count, line, cursor)
        else:                                                   # ordinary character
            before = line[:cursor] + key
            if insert:
                after = line[cursor:]
            else:
                after = line[cursor + 1:]
            line = before + after
            _update_line(insert, cursor, count, line, cursor + 1)
            cursor += 1
            count = len(line)

if __name__ == '__main__':
    test_string = input('test string: ')
    result = mswin_line_edit(test_string)
    print(f'\n{result}')

A: You could do it with tkinter:
from tkinter import *
def enter():
    global commandEntry
    command = commandEntry.get()
    # Do stuff with command
    commandEntry.delete(0, END)
def edit_line(line):
    global commandEntry
    commandEntry.insert(0, line)
root = Tk()
messageVar = StringVar()
messageVar.set("Enter a command:")
message = Label(root, textvariable=messageVar)
commandEntry = Entry(root)
enterButton = Button(root, text="Enter", command=enter)
root.mainloop()

A: You should just have 2 variables: one for standard string, one for string that will user change by itself.
Like:
str1 = 'String that is standard'
str2 = str1 #it usually will be standard string
usr = input('your text goes here')
if len(usr) != 0:
    str2 = usr
#and here goes code for writing string into file


text:
Q: how to make helm hooks retry only one time? I have seen that if my post-upgrade helm hook fails, it retries 5 times before giving up. How do I make sure that the hook only tries once to succeed and give up if failed? Or can I make the helm hook retry only on specific conditions if failed, rather than always?
I could not find any documentation/parameters for this use-case here.

A: You can set Pod backoff failure policy.
As far the k8s doc:
Pod backoff failure policy:
There are situations where you want to fail a Job after some amount of retries due to a logical error in configuration etc. To do so, set .spec.backoffLimit to specify the number of retries before considering a Job as failed. The back-off limit is set by default to 6.
Add backoffLimit: 1 in the pod spec, Ex:
spec:
      containers:
        - name:
          image:
      backoffLimit: 1
      restartPolicy: Never

Full examle:
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ .Release.Name | quote }}
  labels:
    app.kubernetes.io/managed-by: {{ .Release.Service | quote }}
    app.kubernetes.io/instance: {{ .Release.Name | quote }}
  annotations:
    # This is what defines this resource as a hook. Without this line, the
    # job is considered part of the release.
    "helm.sh/hook": post-upgrade
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": hook-succeeded
spec:
  template:
    metadata:
      name: {{ .Release.Name | quote }}
      labels:
        app.kubernetes.io/managed-by: {{ .Release.Service | quote }}
        app.kubernetes.io/instance: {{ .Release.Name | quote }}
    spec:
      backoffLimit: 1
      restartPolicy: Never
      containers:
      - name: post-install-job
        image: "alpine:3.3"
        command: ["/bin/sleep","{{ default "10" .Values.hook.job.sleepyTime }}"]

A: If you want the Helm hook to run just once, you have to set the backoffLimit to 0. That means, it will run and it won't back off, at all.
If you want the hook to retry once after running (and failing), then you have to set backoffLimit to 1 indeed, but that's not the same thing.


text:
Q: How can I truncate filenames after X number of characters using Automator or AppleScript? I have IFTTT sending several new desktop wallpapers per day from Reddit to Dropbox. These wallpapers arrive often with very long filenames. I need a way to automatically shorten their names (without renaming to date and time) when they're downloaded to my Mac by Dropbox.

*

*I want the action to run automatically, so it can't require me to select Finder items or supply the number of characters to keep

*It needs to run by itself as a folder action or AS via Hazel.

Could someone please give me an Automator folder action or AppleScript I can put in Hazel to truncate the filenames after X number of characters?

A: Do we have to be concerned about the names being the same? If not, this should work for you as an embedded AppleScript in Hazel:
tell application "Finder"
    set original_name to name of theFile
    set short_name to characters 1 thru 10 of original_name as string
    set name of theFile to (short_name & ".png" as string)
end tell

You'd set Hazel to run this rule on "any file" then "Run AppleScript" (embedded).
You can change the number of characters easily. I picked ten. Do what works for you. Also, I guessed that your images are ".png" files-- you would change that to ".jpg" or whatever.
I hope this helps you!


text:
Q: injectedJavaScript is not working in Webview of react native I am not able to inject this simple js code into react-native webview.
I referred this link also but no solution provided here.
Then I found this one which works for html props but not uri.
import React, { Component } from 'react';
import { Platform,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

export default class App extends Component<{}> {

  injectjs(){

    let jsCode = 'alert(hello)';
    return jsCode;
  }

  render() {
    return <WebView
    javaScriptEnabled={true}
    injectedJavaScript={this.injectjs()}
    source={{uri:"https://www.google.com"}} style={{ marginTop: 20 }} />;
  }
}

A: Add onMessage method does work.
import React, { Component } from 'react';
import { Platform,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

export default class App extends Component<{}> {
  render() {
    return
      <WebView
        javaScriptEnabled={true}
        injectedJavaScript={'alert("hello")'}
        source={{uri:"https://www.google.com"}} style={{ marginTop: 20 }}
        onMessage={(event) => {
          console.log('event: ', event)
        }}
      />;
  }
}

A: Well, you have more than one issue here.  First one is your web view needs to be wrapped in a containing View component with flex: 1.  Second, injectedJavascript only accepts a string - not a function.  Third, it seems you are attempting to use hello as a variable without defining it, or if it is a string than your syntax needs to be something like this: injectedJavascript={'alert("hello")'}.  Furthermore, injectedJavascript is already fired when the view loads so you are all good there if that's what you are intending to do.  You can inject javascript when the web view starts loading though, using a combination of the props, onLoadStart and injectJavascript, but the implementation is quite different, so that's a different question.  Try this code:
import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

export default class App extends Component {

  render() {
    let yourAlert = 'alert("hello")'
    return (
     <View style={{flex: 1}}>
       <WebView
        javaScriptEnabled={true}
        domStorageEnabled={true}
        injectedJavaScript={yourAlert}
        source={{ uri: "https://www.google.com" }} style={{ marginTop: 20  }} />
    </View>
   )
  }
}

A: You need to add onMessage props.

A: I ran into this issue as well, and I was able to get it to work by setting mixedContentMode:
mixedContentMode={'compatibility'}
see below where props.url = {uri:'https://google.com'} quick test javascript pastes "look at me, I'm injecting" into the search box.
import React from 'react';
import { Button, StyleSheet, Text, View, ScrollView, WebView } from 'react-native';

export class WebViewController extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        const url = this.props.url;
        console.log(`v:1`);
        console.log(`url info: ${JSON.stringify(url)}`);
        console.log(`javascript: ${Constants.javascript.injection}`);
        return (
            <View style={styles.root}>
                <WebView
                    source={url}
                    injectedJavaScript={Constants.javascript.injection}
                    mixedContentMode={'compatibility'}
                    javaScriptEnabled={true}
                    style={styles.webview}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    root: {
        flex:1,
        alignSelf: 'stretch',
    },
    webview: {
        flex:1,
        alignSelf: 'stretch',
    },
})

const Constants = {
    javascript: {
        injection: `
            Array.from(document.getElementsByTagName('input')).forEach((item) => {
                if(item.type == "search") {
                    item.value = "look at me, I'm injecting";
                }
            })
        `
    }
}

I expect the problem is when your adding your html directly and injecting javascript the webview considers the injection as javascript from the same origin.  Unlike when you load a page through a url, where your javascript is foreign and is considered outside of the origin by the default value of mixedContentMode which is 'never'
see: https://facebook.github.io/react-native/docs/webview.html#mixedcontentmode
mixedContentMode
Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin.
Possible values for mixedContentMode are:
'never' (default) - WebView will not allow a secure origin to load content from an insecure origin.
'always' - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure.
'compatibility' - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content.

A: https://github.com/react-native-webview/react-native-webview/blob/master/docs/Guide.md#the-injectjavascript-method
follow this link

The injectJavaScript method

While convenient, the downside to the previously mentioned
injectedJavaScript prop is that it only runs once. That's why we
also expose a method on the webview ref called injectJavaScript
(note the slightly different name!).

A: Adding a empty ref & onMessage fixed this for me:
onMessage={(event) => {}}
ref={() => {}}

A: For anyone struggling with this in 2021, what I ended up having to do (pretty dirty solution but it worked), was to poll for the necessary dependencies I was injecting into the window object via injectedJavaScriptBeforeContentLoaded, and only running the rest of my code when they became available.
My solution ended up looking something like this:
function app () {
    // Continue to re-call self until frame data is available
    if (typeof window._rendererFrameData === 'undefined') {
        setTimeout(app, 250);
        return;
    }

    // Passed in from RN
    var size = window._rendererSize;
    var pixelSize = window._rendererPixelSize;

    // Picture data
    var frames = [];
    window._rendererFrameData.forEach(function(frameString) {
        frames.push(frameString.split(''));
    });
    var frameIndex = 0;

    var canvas = document.querySelector('canvas');
    canvas.setAttribute('width', size * pixelSize + 2);
    canvas.setAttribute('height', size * pixelSize + 2);
    document.body.setAttribute('width', size * pixelSize + 2);
    document.body.setAttribute('height', size * pixelSize + 2);

    var ctx = canvas.getContext('2d');

    // ... rest of renderer logic
}

app();

Note the if statement w/ setTimeout and return at the start. Basically it checks if my injected data is undefined, then queues the function to re-run in 250 milliseconds and bails out. This continues until the data is available.
Feels like a seriously bad case of band-aid solution, but it works for my app!


text:
Q: File Upload not working with Angular and Node.JS I'm having issues getting file upload to work with the Angular ng-File-Upload module and my Node.js server. In the examples it says that I should be able to access the files that came across in the client request via a "file" or "files" attribute (req.file or req.files).However such attributes upon request are "undefined" and I can find no trace of the files in the client request.
My client side code looks like this:
$scope.addFiles = function(files){
        console.log(files);
        $scope.information.files = files;
            Upload.upload({
                url: 'http://www.uploadURL.com/uploadFiles',
                file: files
            }).progress(function(evt){
                console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total) + '% file :'+ evt.config.file.name);
            }).success(function(data, status){
                console.log('data '+ data);
                console.log('status '+status);
            }).error(function(data, status){
                console.log('bad data '+ data);
                console.log('bad status '+ data);
            });
        }
    };

The line of HTML for uploading looks like this:
<button class="btn btn-primary btn-lg btn-block uploadButton" type="file" ngf-select="addFiles($files)" multiple accept="*"> Select Files</button>

and the server side currently looks like this:
app.post('/uploadFiles', function(req, res){
        var tempfiles = [];
        console.log(req.file);
        console.log(req.files);
});

Both of the above console logs return "undefined". If anyone has any idea on how to fix this/ a better method for file upload I would be extremely grateful.

A: The post data is in the body of the request and you would need the body-parser middleware to parse the post data and set it as fields on the request. Check this out


text:
Q: How to build and run a Ruby command-line tool found on github? Hi cloned a simple app ( https://github.com/cfx/twix) on github that allows me to send Twitter messages from the console, but I'm not sure how to run it.
I now have a folder in my users/name director called Twix. Inside twix, I have these folders created by the app.
README      Rakefile    bin     lib     test

The readme doesn't provide a lot of instruction to get things started. It just tells you what to do after the program's running (see below).
Questions: What command do I use to get this started? What folder do I need to be in?
The README
Twix 0.0.1

Simple twitter client for console

Keys:

q - quit
t - write new message

If you want to post your twit, finish you message with !SEND
If you want abort and back to your feed, finish your message with !EXIT

new features soon

A: This program is packaged as a gem. The following command will install the gem (run it in the Twix directory):
rake package && gem install pkg/twix-0.0.1.gem

You can now run the program from anywhere with the twix command.
Edit
The first thing I saw in the repository was the Rakefile, meaning there were some rake tasks defined. When you find yourself in this case, running rake -T is your best bet as it will show you the rake tasks available. Its output was the following:
(in /home/benoit/code/clones/twix)
rake clobber_package  # Remove package products
rake gem              # Build the gem file twix-0.0.1.gem
rake package          # Build all the packages
rake repackage        # Force a rebuild of the package files

I picked the command that would be the most likely to build the gem: the package one. I guess the gem task would have worked as well.
Running rake package gave me the following output:
(in /home/benoit/code/clones/twix)
mkdir -p pkg
WARNING:  no homepage specified
  Successfully built RubyGem
  Name: twix
  Version: 0.0.1
  File: twix-0.0.1.gem
mv twix-0.0.1.gem pkg/twix-0.0.1.gem

All that was left was to install the pkg/twix-0.0.1.gem created by the previous command:
gem install pkg/twix-0.0.1.gem

There's another case you could have encountered: the presence of a twix.gemspec in the root directory of the application. In this case, running:
gem build twix.gemspec

would have built the gem, the installation step remains the same.

A: ruby ./bin/twix

or
ruby -I lib ./bin/twix